dev-seahouse
dev-seahouse

Reputation: 163

How to use xPath?

I got the following xml file from web service response, how do i retrieve the value of like say location and store into a string in visual studio? I tried the following code:

XmlNode root = wsResponseXmlDoc.DocumentElement;
XmlNode currentWeather = root.SelectSingleNode("/CurrentWeather/Location");

But it's giving me 'System.NullReferenceException' Error. Please Help!

 <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetWeatherResponse xmlns="http://www.webserviceX.NET"><GetWeatherResult>&lt;?xml version="1.0" encoding="utf-16"?&gt;
    &lt;CurrentWeather&gt;
      &lt;Location&gt;Siemreap, Cambodia (VDSR) 13-22N 103-51E 15M&lt;/Location&gt;
      &lt;Time&gt;Dec 22, 2013 - 01:00 PM EST / 2013.12.22 1800 UTC&lt;/Time&gt;
      &lt;Wind&gt; Variable at 2 MPH (2 KT):0&lt;/Wind&gt;
      &lt;Visibility&gt; 4 mile(s):0&lt;/Visibility&gt;
      &lt;SkyConditions&gt; partly cloudy&lt;/SkyConditions&gt;
      &lt;Temperature&gt; 66 F (19 C)&lt;/Temperature&gt;
      &lt;DewPoint&gt; 60 F (16 C)&lt;/DewPoint&gt;
      &lt;RelativeHumidity&gt; 82%&lt;/RelativeHumidity&gt;
      &lt;Pressure&gt; 29.91 in. Hg (1013 hPa)&lt;/Pressure&gt;
      &lt;Status&gt;Success&lt;/Status&gt;
    &lt;/CurrentWeather&gt;</GetWeatherResult></GetWeatherResponse></soap:Body></soap:Envelope>

Upvotes: 0

Views: 108

Answers (1)

t0mppa
t0mppa

Reputation: 4078

Two things:

  1. If your file is really having escaped &lt; and &gt; instead of < and >, it won't be parsed as proper XML on those parts, rather than one big tag with tons of weird text in it.

  2. Starting your xpath with a single / means you're looking for root element, which obviously in your case is not found under the name CurrentWeather. If you use //, it means you're skipping elements until the following elements are found. Thus, try //CurrentWeather/Location.

    For more explanations about xpath syntax, see here.

Upvotes: 5

Related Questions