Snedden27
Snedden27

Reputation: 1930

Why does selectSingleNode of an Xml Document has null value?

This is my XML file :

<Response>
<Ip>120.63.40.84</Ip>
<CountryCode>IN</CountryCode>
<CountryName>India</CountryName>
<RegionCode>07</RegionCode>
<RegionName>Delhi</RegionName>
<City>New Delhi</City>
<ZipCode/>
<Latitude>28.6</Latitude>
<Longitude>77.2</Longitude>
<MetroCode/>
</Response>

This is how I load it to an XML document object in C#:

  XmlDocument doc = new XmlDocument();
  doc.Load("http://freegeoip.net/xml/");//the url

but when I try to read an individual node like this:

XmlNode IPnode = doc.DocumentElement.SelectSingleNode("Response/Ip");

its gives me a null node. I have debugged the code and confirmed that the XML does load in the XMLDocument object but for some reason I can't get to the individual node like this.

Upvotes: 2

Views: 12834

Answers (2)

mormegil
mormegil

Reputation: 1880

A simpler, perhaps faster implementation (that side-steps XPath expression parsing) than @ryadavilli's would be:

XmlNode IPnode = doc.DocumentElement["Ip"];

... which should find the first child element of the document element which has a tag name of "Ip".

Upvotes: 2

Ravi Y
Ravi Y

Reputation: 4376

Just change your XPath to indicate you are trying to search from the root.

 XmlNode IPnode = doc.DocumentElement.SelectSingleNode("/Response/Ip");

Since you are searching from the document element anyway, you can also use the code below.

 XmlNode IPnode = doc.DocumentElement.SelectSingleNode("Ip");

Upvotes: 5

Related Questions