Why does selectSingleNode of an Xml Document has null value?

12,022

Solution 1

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");

Solution 2

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".

Share:
12,022
Snedden27
Author by

Snedden27

A rookie programmer , trying to learn more about computing

Updated on June 14, 2022

Comments

  • Snedden27
    Snedden27 almost 2 years

    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.