Search code examples
c#xmlxpathselectsinglenode

C# Xml SelectSingleNode returns null


I have this xml and want to extract the first Country out of the xml

<string xmlns="http://www.webserviceX.NET">
   <NewDataSet>
      <Table>
         <Country>Hong Kong</Country>
         <City>Cheung Chau</City>
      </Table>
      <Table>
         <Country>Hong Kong</Country>
         <City>Hong Kong Inter-National Airport</City>
      </Table>
   </NewDataSet>
</string>

here's what I did:

value = xml.DocumentElement.SelectSingleNode("string/NewDataSet/Table[1]/Country").InnerText;

This always throw an exception not set to an instance of object as the selectsinglenode always retursn null. Strange thing is I have already tested this xpath using this and it does return me the node I want.

I have googled to find a solution and found this suggesting that I have to add namespace, here's what I did:

  var nsmgr = new XmlNamespaceManager(xml.NameTable);
  nsmgr.AddNamespace("string", "http://www.webserviceX.NET");
  var node = xml.DocumentElement.SelectSingleNode("string/NewDataSet/Table[1]/Country", nsmgr);

Still I have the same exception. Can someone please let me know what I'm doing wrong here? Thanks :)


Solution

  • Just use XmlNamespaceManager

    XmlNamespaceManager namespaces = new XmlNamespaceManager(xdoc.NameTable);
    namespaces.AddNamespace("sp", "http://www.webserviceX.NET");
    var nodes = xdoc.DocumentElement.SelectSingleNode("//sp:NewDataSet/sp:Table[1]/sp:Country", namespaces);