我知道以前曾以类似的方式问过这个问题,但我似乎无法解决这个问题。
我有一些 xml:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<Research xmlns="http://www.rixml.org/2005/3/RIXML" xmlns:xalan="http://xml.apache.org/xalan" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" createDateTime="2011-03-29T15:41:48Z" language="eng" researchID="MusiJvs3008">
<Product productID="MusiJvs3008">
<StatusInfo currentStatusIndicator="Yes" statusDateTime="2011-03-29T15:41:48Z" statusType="Published" />
<Source>
<Organization type="SellSideFirm" primaryIndicator="Yes">
<OrganizationID idType="Reuters">9999</OrganizationID>
我正在尝试使用 xpath 读取值:
XPathDocument xmldoc = new XPathDocument(xmlFile);
XPathNavigator nav = xmldoc.CreateNavigator();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace(string.Empty, "http://www.rixml.org/2005/3/RIXML");
XPathNavigator result = nav.SelectSingleNode("/Research", nsMgr); // <-- Returns null!
但即使是简单地选择根节点也会返回 null!我确信我的命名空间有问题。有人可以帮忙吗?
理想情况下,我想要简单的行,让我从 xml 文件中选择值,即
String a = xmlDoc.SelectSingleNode(@"/Research/Product/Content/Title").Value;
顺便说一句,我无法(直接)控制 XML 文件内容。
我不相信您可以使用空的命名空间别名并让 XPath 表达式自动使用它。一旦您使用实际的别名,它就应该可以工作。这个测试很好,例如:
using System;
using System.Xml;
using System.Xml.XPath;
class Test
{
static void Main()
{
string xmlFile = "test.xml";
XPathDocument xmldoc = new XPathDocument(xmlFile);
XPathNavigator nav = xmldoc.CreateNavigator();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML");
XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr);
Console.WriteLine(result);
}
}
Do you have使用 XPath 和XPathDocument
, 顺便一提?我倾向于发现 LINQ to XML 是much更令人愉快的 API,特别是在涉及命名空间时。如果您使用 .NET 3.5 并且没有使用 XPath 的特殊要求,我建议您检查一下。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)