简体   繁体   English

使用C#解析从服务返回的XML字符串

[英]Parse XML string returned from service with C#

I'm trying to parse the following XML string that is being returned from a service. 我正在尝试解析从服务返回的以下XML字符串。

 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. 我只想显示结果,例如City = Marana,State = AZ等。

Any help is appreciated. 任何帮助表示赞赏。

Why not just use XPath? 为什么不只使用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: 您可以创建一个序列化对象,然后序列化针对该对象获得的数据,我使用http://xmltocsharp.azurewebsites.net/生成了以下xml对象:

[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. 然后,只需使用.net XML序列化程序将其转换为该对象,然后在代码中使用它即可。

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 如果您只需要一个字符串即可进行视觉检查,则第一步可能是使用以下代码将XMl转换为JSON: 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. 然后,您可以继续删除括号,用换行符替换逗号,并用等号替换冒号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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