Peut trouver des descendants en utilisant LINQ to XML ou extensions XPath
-
19-09-2019 - |
Question
Tout le monde connaît le problème pourquoi LINQ to XML ou extensions de XPath cant semblent lire ce 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
La solution
Vous devez référencer l'espace de noms
par exemple.
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);
}
Autres conseils
Le problème est en effet l'espace de noms. Cela pourrait résoudre votre problème.
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
);
Ces XPath fonctionne aussi:
var xProducts = document.XPathSelectElements("//n:Products/n:Product", manager);
var xProducts = document.XPathSelectElements("//n:Product", manager);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow