简体   繁体   中英

Parse XML string returned from service with C#

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.

Any help is appreciated.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM