2

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 :)

sunsun
  • 33
  • 1
  • 5
  • 1
    In that answer you missed that the namespace is added to a node by prepending it to the nodename with a colon. As you named you namespace `string` you'll have to prepend all nodenames with `string:` so you'll get `string:string\string:NewDataSet\...` etc. – rene Dec 19 '17 at 07:18
  • Your root node has a [default XML namespace](https://en.wikipedia.org/wiki/XML_namespace) so see [XmlDocument.SelectSingleNode and xmlNamespace issue](https://stackoverflow.com/q/4171451/3744182). Recent related question: [How to get xml tag which is in DataSet1 tag(C#)?](https://stackoverflow.com/q/47829282/3744182) with associated fiddle https://dotnetfiddle.net/I25p6S showing how to do it correctly. – dbc Dec 19 '17 at 07:22
  • @rene those should be `/` not \ (backslash) characters I believe. – dbc Dec 19 '17 at 07:25
  • @dbc Oh, yeah, you're right, I'm on my first coffee, you can tell. Sorry about that. – rene Dec 19 '17 at 07:29

1 Answers1

2

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);
lucky
  • 12,734
  • 4
  • 24
  • 46