Question

I have created the following xml file:

<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
  <channel>
    <item>
      <g:id>6945</g:id>
      <g:price>1222.00</g:price>
    </item>
  </channel>
</rss>

I need to use the g:id to find the item node because in the real xmlfile I have hundreds of items. However at the moment I am trying to select itemnode but this is null?:

XNamespace g = "http://base.google.com/ns/1.0";
var doc = XDocument.Load(Server.MapPath("~/xmlfile1.xml"));
var reader = doc.CreateReader();
var namespaceManager = new XmlNamespaceManager(reader.NameTable);
namespaceManager.AddNamespace("g", g.NamespaceName);
var itemNode = doc.XPathSelectElement("/Channel/item/g:id[text()= 6945]", namespaceManager);
Was it helpful?

Solution

The XPath you're using is incorrect. Following should work:

var itemNode = doc.XPathSelectElement("//channel/item/g:id[text()= 6945]", namespaceManager);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top