Link to home
Create AccountLog in
Avatar of rmartes
rmartes

asked on

How to select xml nodes from webservice xml file.

Hello Experts,

As an overview, I needed some way to retrieve timezone by zipcode, so I found a web service that returns an xml file when accessed as so:

http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=+MYZIPCODE+

This is what it returns:

<?xml version="1.0" encoding="utf-8" ?>
- <NewDataSet>
- <Table>
  <CITY>Hayward</CITY>
  <STATE>CA</STATE>
  <ZIP>94541</ZIP>
  <AREA_CODE>510</AREA_CODE>
  <TIME_ZONE>P</TIME_ZONE>
  </Table>
  </NewDataSet>

I need to grab the TIME_ZONE node, but not sure how to....help anyone?

Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of rmartes
rmartes

ASKER

Thanks Carl,

Its pretty straight forward, but when I tried it, I get a "Data at the root level is invalid. Line 1, position 1."

Any suggestions?
Can you post what you have? If the XML you posted is precisely what you have then it should be fine. The two hyphens should be there, but I assume they're just there because you copied and pasted from a browser.
Give this a shot.  It reads the data directly into an XMLNode.

 
ServiceReference1.USZipSoapClient sr = new ServiceReference1.USZipSoapClient();

			XmlNode node = sr.GetInfoByZIP("10018");

			Console.WriteLine(String.Format("{0} {1} {2} {3} {4}"
			,node.SelectSingleNode("Table/CITY").InnerText
			,node.SelectSingleNode("Table/STATE").InnerText
			,node.SelectSingleNode("Table/ZIP").InnerText
			,node.SelectSingleNode("Table/AREA_CODE").InnerText
			,node.SelectSingleNode("Table/TIME_ZONE").InnerText
			));

Open in new window

Avatar of rmartes

ASKER

Here is my code:

XmlDocument doc = new XmlDocument();
doc.LoadXml("http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=10460");

XmlNode timezone = doc.SelectSingleNode("/NewDataSet/Table/TIME_ZONE");
string tz = timezone.InnerText;

Response.Write(tz);

Here is the xml file returned by the web service:

<?xml version="1.0" encoding="utf-8" ?>
<NewDataSet>
 <Table>
  <CITY>Hayward</CITY>
  <STATE>CA</STATE>
  <ZIP>94541</ZIP>
  <AREA_CODE>510</AREA_CODE>
  <TIME_ZONE>P</TIME_ZONE>
 </Table>
</NewDataSet>
Your code should work if you use doc.Load() instead of doc.LoadXml()...

doc.Load("http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=10460");
Avatar of rmartes

ASKER

Great