1

任何人都知道为什么linq to xmlxpath 扩展似乎无法读取此 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


4

2 回答 2

1

您需要引用命名空间

例如

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);
}      
于 2010-01-08T15:50:16.373 回答
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);
于 2010-01-08T16:36:27.133 回答