3

我知道以前曾以类似的方式提出过这个问题,但我似乎无法解决这个问题。

我有一些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 文件内容。

4

3 回答 3

5

我不相信您可以使用空的命名空间别名并让 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);
    }
}

顺便说一句,您是否必须使用 XPath 和XPathDocument?我倾向于发现 LINQ to XML 是一个令人愉悦的 API,尤其是在涉及名称空间时。如果您使用的是 .NET 3.5,并且对使用 XPath 没有特别要求,我建议您检查一下。

于 2011-03-30T16:16:51.623 回答
3

进行以下更改

nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML"); 
XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr);
于 2011-03-30T16:17:41.130 回答
0

对于此代码的本机等效项,我可以发布并回答我自己的问题。相反,我将其添加为最后的答案。

使用本机IXMLDOMDocument(版本 6)对象时:

//Give the default namespace as alias of "x"
document.setProperty("SelectionNamespaces","xmlns:x='http://www.rixml.org/2005/3/RIXML'");

//Query for the nodes we want
document.selectSingleNode("/x:Research");

奖励问题:为什么,哦,为什么,当没有指定命名空间时,没有 Xml 文档对象模型查询默认命名空间......叹息

于 2012-05-29T02:34:21.477 回答