SelectSingleNode返回null – 即使是命名空间

我知道这个问题之前已经以类似的方式提出过,但我似乎无法让这个问题起作用。

我有一些xml:

      9999 

我正在尝试使用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); } } 

顺便问一下,你必须使用XPath和XPathDocument吗? 我倾向于发现LINQ to XML是一个更令人愉快的API,特别是在命名空间方面。 如果您使用的是.NET 3.5并且没有特别要求使用XPath,我建议您查看它。

进行以下更改

 nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML"); XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr); 

我可以发布并回答我自己的问题,因为这个代码的原生等价物。 相反,我只是将它作为答案添加到最后。

使用本机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 Document对象模型在没有指定命名空间时查询默认命名空间… 叹息