Can find descendants using LINQ to XML or XPath Extensions
-
19-09-2019 - |
Question
Anyone knows the problem why linq to xml or xpath extensions cant seem to read this 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
Solution
You need to reference the namespace
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);
}
OTHER TIPS
The problem is indeed the namespace. This might solve your problem.
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
);
These XPath also works:
var xProducts = document.XPathSelectElements("//n:Products/n:Product", manager);
var xProducts = document.XPathSelectElements("//n:Product", manager);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow