Gulumal
Gulumal

Reputation: 53

XPath query not working in C#

I have the following XML.

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog xmlns="urn:ihe:iti:xds-b:2007">
  <cd country="USA">
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <price>10.90</price>
  </cd>
  <cd country="UK">
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <price>10.0</price>
  </cd>
  <cd country="USA">
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <price>9.90</price>
  </cd>
</catalog>

------------------- And Following code---

var document = new XmlDocument();
document.Load(@"C:\Temp\tmp\data1.xml");
var nsmgr = new XmlNamespaceManager(document.NameTable);
var nl = document.SelectNodes("catalog/cd[@country='UK']", nsmgr);

document.SelectNodes won't return anything. When I remove the name space on the element Catalog ( second line of the xml) it works fine. So its something with the namespace. How do I make it work? what am I doing wrong?

thanks gulumal

Upvotes: 2

Views: 64

Answers (1)

Bensonius
Bensonius

Reputation: 1541

I believe you'll need to add the namespace from the document into your NamespaceManager

 var nsmgr = new XmlNamespaceManager(document.NameTable);
 // add extra namespace with prefix "s"
 nsmgr.AddNamespace("s", "urn:ihe:iti:xds-b:2007");

Then you query do like so (notice the use of "s" as a namespace prefix):

 var nl = document.SelectNodes("s:catalog/s:cd[@country='UK']", nsmgr);

Upvotes: 1

Related Questions