【问题标题】:parsing xml returned by web service response解析 Web 服务响应返回的 xml
【发布时间】:2013-01-03 23:15:24
【问题描述】:

我已经阅读了很多关于这个主题的问题,但我似乎与我正在尝试做的事情有关。基本上,我正在调用 Web 服务来返回有关车辆识别号 (VIN) 的信息。它返回一个如下所示的 xml 流:

<VINquery Version="1.0.0" Date="5/25/2003">
  <VIN Number="1HGES15501Lxxxxxx" Status="SUCCESS">
    <Vehicle VINquery_Vehicle_ID="23261" Model_Year="2001" Make="Honda" Model="Civic" Trim_Level="LX Sedan">
      <Item Key="VINquery Vehicle ID" Value="23261" Unit=""/>
      <Item Key="Model Year" Value="2001" Unit=""/>
      <Item Key="Make" Value="Honda" Unit=""/>
      <Item Key="Model" Value="Civic" Unit=""/>
      <Item Key="Trim Level" Value="LX Sedan" Unit=""/>
      <Item Key="Manufactured in" Value="UNITED STATES" Unit=""/>
      <Item Key="Production Seq. Number" Value="xxxxxx" Unit=""/>
      <Item Key="Body Style" Value="SEDAN 4-DR" Unit=""/>
      <Item Key="Engine Type" Value="1.7L L4 SOHC 16V" Unit=""/>
      <Item Key="Transmission-short" Value="5M OD" Unit=""/>
      <Item Key="Transmission-long" Value="5-Speed Manual Overdrive" Unit=""/>
      <Item Key="Driveline" Value="FWD" Unit=""/>
      <Item Key="Tank" Value="13.20" Unit="gallon"/>
      <Item Key="Fuel Economy-city" Value="30 - 32" Unit="miles/gallon"/>
      <Item Key="Fuel Economy-highway" Value="38 - 39" Unit="miles/gallon"/>
      <Item Key="Anti-Brake System" Value="Non-ABS" Unit=""/>
      <Item Key="Steering Type" Value="R&P" Unit=""/>
      <Item Key="Standard Seating" Value="5" Unit=""/>
      <Item Key="Optional Seating" Value="No data" Unit=""/>
      <Item Key="Length" Value="174.60" Unit="in."/>
      <Item Key="Width" Value="67.50" Unit="in."/>
      <Item Key="Height" Value="56.70" Unit="in."/>
    </Vehicle>
  </VIN>
</VINquery>

我想获取这些数据并为每个键/值解析它。 这是我正在使用获取 xml 数据的代码:

private string baseURL = "http://ws.vinquery.com/restxml.aspx?accessCode=xxxxxx&vin=xxxxxxxxx";
private string reportType = "&reportType=2";

public XmlDocument ExplodeVIN(string strVIN)
{
   DataTable dt = new DataTable();

   string url = baseURL + strVIN + reportType;

   HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;

   XmlDocument xmlDoc = new XmlDocument();
   using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
   {
     xmlDoc.Load(resp.GetResponseStream());
   }
   return xmlDoc;
}

获得 xmlDoc 后,我不知道下一步该做什么。

感谢您的热心帮助。

【问题讨论】:

    标签: c# web-services xml-parsing


    【解决方案1】:

    您可以使用 Linq to Xml 将 xml 解析为 Dictionary&lt;string, string&gt;

    var xdoc = XDocument.Parse(xml);
    var items = xdoc.Descendants("Item")
                    .ToDictionary(i => (string)i.Attribute("Key"),
                                  i => (string)i.Attribute("Value"));
    

    用法:

    string driveline = items["Driveline"];
    

    或者

    foreach(var kvp in items)
        // use key value pair
    

    【讨论】:

    • 我不明白你的行:var xdoc = XDocument.Parse(xml)。 parse 方法查找字符串。字符串 xml 来自哪里?
    • @Ryan 应该是服务响应字符串。如果您有响应流,请改用XDocument.Load(stream)
    • 这似乎正在接近...var items = xdoc.Descendants("Item").ToDictionary(i => (string)i.Element("Key"), i => ( string)i.Element("值​​"));导致参数 null 异常,我不知道为什么
    • @Ryan 对不起,我的错。 Key 和 Value 是属性,而不是元素。我有固定的代码。此外,您还没有在 xml 中为 Steering Type 键转义 & 符号。 & 符号应转义为 &amp;amp;
    【解决方案2】:
    XmlDocument xmldoc = new XmlDocument();
    XmlNodeList xmlnodelstTrack = xmldoc.GetElementsByTagName("Item");
    foreach (XmlNode NodeObj in xmlnodelstTrack)
    {
      //Do stuff with NodeObj.OuterXml
    
    }
    

    【讨论】:

    • 我也喜欢这个解决方案。在我的 xml 示例中,我会通过“Vehicle”节点来获取 Item 节点键/值吗?还是应该在循环时传递“项目”来获取键/值?
    【解决方案3】:

    我通常使用另一种方式来处理 xml。

    第 1 步:复制您的 xml 字符串并粘贴为类。

    粘贴的时候会自动生成这段代码:

            /// <remarks/>
            [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
            [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
            public partial class VINquery
            {
    
                private VINqueryVIN vINField;
    
                private string versionField;
    
                private string dateField;
    
                /// <remarks/>
                public VINqueryVIN VIN
                {
                    get
                    {
                        return this.vINField;
                    }
                    set
                    {
                        this.vINField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Version
                {
                    get
                    {
                        return this.versionField;
                    }
                    set
                    {
                        this.versionField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Date
                {
                    get
                    {
                        return this.dateField;
                    }
                    set
                    {
                        this.dateField = value;
                    }
                }
            }
    
            /// <remarks/>
            [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
            public partial class VINqueryVIN
            {
    
                private VINqueryVINVehicle vehicleField;
    
                private string numberField;
    
                private string statusField;
    
                /// <remarks/>
                public VINqueryVINVehicle Vehicle
                {
                    get
                    {
                        return this.vehicleField;
                    }
                    set
                    {
                        this.vehicleField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Number
                {
                    get
                    {
                        return this.numberField;
                    }
                    set
                    {
                        this.numberField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Status
                {
                    get
                    {
                        return this.statusField;
                    }
                    set
                    {
                        this.statusField = value;
                    }
                }
            }
    
            /// <remarks/>
            [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
            public partial class VINqueryVINVehicle
            {
    
                private VINqueryVINVehicleItem[] itemField;
    
                private ushort vINquery_Vehicle_IDField;
    
                private ushort model_YearField;
    
                private string makeField;
    
                private string modelField;
    
                private string trim_LevelField;
    
                /// <remarks/>
                [System.Xml.Serialization.XmlElementAttribute("Item")]
                public VINqueryVINVehicleItem[] Item
                {
                    get
                    {
                        return this.itemField;
                    }
                    set
                    {
                        this.itemField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public ushort VINquery_Vehicle_ID
                {
                    get
                    {
                        return this.vINquery_Vehicle_IDField;
                    }
                    set
                    {
                        this.vINquery_Vehicle_IDField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public ushort Model_Year
                {
                    get
                    {
                        return this.model_YearField;
                    }
                    set
                    {
                        this.model_YearField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Make
                {
                    get
                    {
                        return this.makeField;
                    }
                    set
                    {
                        this.makeField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Model
                {
                    get
                    {
                        return this.modelField;
                    }
                    set
                    {
                        this.modelField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Trim_Level
                {
                    get
                    {
                        return this.trim_LevelField;
                    }
                    set
                    {
                        this.trim_LevelField = value;
                    }
                }
            }
    
            /// <remarks/>
            [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
            public partial class VINqueryVINVehicleItem
            {
    
                private string keyField;
    
                private string valueField;
    
                private string unitField;
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Key
                {
                    get
                    {
                        return this.keyField;
                    }
                    set
                    {
                        this.keyField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Value
                {
                    get
                    {
                        return this.valueField;
                    }
                    set
                    {
                        this.valueField = value;
                    }
                }
    
                /// <remarks/>
                [System.Xml.Serialization.XmlAttributeAttribute()]
                public string Unit
                {
                    get
                    {
                        return this.unitField;
                    }
                    set
                    {
                        this.unitField = value;
                    }
                }
            }
    

    第 2 步: 将你的 xml 字符串反序列化为这个生成的类。

    public T DeserializeXML<T>(string xmlContent)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlContent));
        return (T)serializer.Deserialize(memStream);
    }
    
    ....
    string resultXml = resp.GetResponseStream();
    VINquery resultObject = DeserializeXML<VINquery>(resultObject); 
    

    现在您可以轻松地操作和过滤您的结果。

    P.S.:您必须删除 xml 字符串中的特殊字符 (&),因为当您尝试将其粘贴为类时会导致问题。

    【讨论】:

    • 在响应为 10Mb 即极长时使用此方法的任何提示?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2017-07-04
    • 2022-01-14
    • 2016-03-27
    • 1970-01-01
    相关资源
    最近更新 更多