0

I'm trying to parse the following XML string that is being returned from a service.

 DataReference.USZipSoapClient blah = new DataReference.USZipSoapClient("USZipSoap");
        var results = blah.GetInfoByCity(tbCityName.Text).OuterXml;

returns the following

<NewDataSet xmlns=""><Table><CITY>Marana</CITY><STATE>AZ</STATE><ZIP>85653</ZIP><AREA_CODE>520</AREA_CODE><TIME_ZONE>M</TIME_ZONE></Table></NewDataSet>

I'm having no luck parsing the data:

I just want to display the results like City = Marana, State = AZ etc.

2
  • 4
    Parsing XML files is a mature problem and is documented all over the place. I suggest you start by reading about System.Xml.Linq.XDocument. Commented Feb 24, 2016 at 8:20
  • 2
    Well what have you tried to parse the data? Commented Feb 24, 2016 at 8:20

3 Answers 3

1

Why not just use XPath?

XmlDocument doc = new XmlDocument()
doc.LoadXml(results); // probably some try-catch here
var city = doc.SelectSingleNode("//CITY").InnerXml; //Handle null as well
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a serializing object and then serialize the data you get against that object, i used http://xmltocsharp.azurewebsites.net/ to generate the following xml object:

[XmlRoot(ElementName="Table")]
public class Table {
    [XmlElement(ElementName="CITY")]
    public string CITY { get; set; }
    [XmlElement(ElementName="STATE")]
    public string STATE { get; set; }
    [XmlElement(ElementName="ZIP")]
    public string ZIP { get; set; }
    [XmlElement(ElementName="AREA_CODE")]
    public string AREA_CODE { get; set; }
    [XmlElement(ElementName="TIME_ZONE")]
    public string TIME_ZONE { get; set; }
}

[XmlRoot(ElementName="NewDataSet")]
public class NewDataSet {
    [XmlElement(ElementName="Table")]
    public Table Table { get; set; }
    [XmlAttribute(AttributeName="xmlns")]
    public string Xmlns { get; set; }
}

Then just use the .net XML serializer to cast it to that object and use it in your code.

1 Comment

That's a very interesting service. Thank you for this info!
0

If you just need a string for visual inspection, a first step could be to convert the XMl to JSON with this code: http://techhasnoboundary.blogspot.no/2011/08/convert-xml-to-json-using-c.html

Then you could go on by removing braces, replace comma with line break and colon with an equal sign.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.