Reputation: 115
I'm trying to return certain lines from an XML.
<geoip>
<source>smart-ip.net</source>
<host>68.9.63.33</host>
<lang>en</lang>
<countryName>United States</countryName>
<countryCode>US</countryCode>
<city>West Greenwich</city>
<region>Rhode Island</region>
<latitude>41.6298</latitude>
<longitude>-71.6677</longitude>
<timezone>America/New_York</timezone>
</geoip>
I was getting full dump before but now I'm using this code...
Which is giving me null
for name
when I click submit. Not sure why it's not reading the XML call.
Here is my code...
try {
WebClient wc = new WebClient();
var xml = wc.DownloadString(string.Format("http://smart-ip.net/geoip-xml/",
txtIP.Text));
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var name = doc.DocumentElement.SelectSingleNode("//geoip/countryName").Value;
txtIPresults.Text = name;
} catch (Exception myException) {
throw new Exception("Error Occurred:", myException);
}
Upvotes: 0
Views: 82
Reputation: 11953
Beside using InnerText
as Jon correctly suggest, try:
var name = doc.DocumentElement.SelectSingleNode("countryName").InnerText;
I think you problem is that doc.DocumentElement
is already the geoip
XML element, and so you need just to get its countryName
child.
Alternatively:
var name = doc.SelectSingleNode("//geoip/countryName").InnerText;
Upvotes: 1
Reputation: 803
The XML you are searching with SelectSingleNode
does not contain a path that matches your parameter. The default return for that function is null - so when your path isn't found null
is returned.
Also, when I try to visit the webpage you specified I am getting a server error. I recommend that you at least check to make sure that your xml
variable has content.
(EDIT)
After reviewing the XML, I noticed that you are calling Value
on the single node returned. You don't want the value, you want the InnerText
property - there you will find the value you are looking for.
Upvotes: 2