可以使用LINQ to XML或XPath Extensions找到后代

时间:2010-01-08 04:33:32

标签: .net xpath linq-to-xml xml-namespaces

任何人都知道为什么 linq to xml xpath扩展似乎无法读取此xml?

http://www.quillarts.com/Test/product.xml


var document = XDocument.Load(feedUrl);
var xpathxml = from feed in document.XPathSelectElements("//Products") //using Xpath
var linqtoxml = from feed in document.Descendants("Products") //using Linq2XML


2 个答案:

答案 0 :(得分:1)

您需要引用命名空间

e.g。

var document = XDocument.Load(...);
XNamespace xmlns = "urn:yahoo:prods";

var linqtoxml = from feed in document.Descendants(xmlns + "Products") select feed;
foreach (var p in linqtoxml)
{
    System.Diagnostics.Debug.WriteLine(p);
}      

答案 1 :(得分:1)

问题确实是命名空间。这可能会解决您的问题。

var document = XDocument.Load(feedUrl);

XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("n", "urn:yahoo:prods");

var xProducts = document.XPathSelectElements(
    "/n:ProductSearch/n:Products/n:Product", manager
);

这些XPath也有效:

var xProducts = document.XPathSelectElements("//n:Products/n:Product", manager);
var xProducts = document.XPathSelectElements("//n:Product", manager);