views:

278

answers:

2

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


+1  A: 

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);
}      
James
+1  A: 

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);
jpbochi