将XML转换为C#对象

时间:2017-03-30 05:58:04

标签: c# xml

我需要从这些xml数据中获取OrderID:

<?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>

我试过这个但是没有用。

var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}

请建议。

5 个答案:

答案 0 :(得分:2)

对于这样的问题,我总是选择使用XmlSerializer。 使用这个类:

    using System;
    using System.Xml.Serialization;
    using System.Collections.Generic;
    namespace classes
    {
        [XmlType(Namespace = "urn:ebay:apis:eBLBaseComponents")]
   public class Order
    {
        public int OrderID { get; set; }
        public string OrderStatus { get; set; }
    }

    [XmlType(Namespace = "urn:ebay:apis:eBLBaseComponents")]
    public class OrderArray
    {
        public List<Order> Orders { get; set; }
    }

    [XmlRoot(Namespace = "urn:ebay:apis:eBLBaseComponents")]
    public class GetOrdersResponse
    {
        public string Timestamp { get; set; }
        public string Ack { get; set; }
        public string Version { get; set; }
        public string Build { get; set; }
        public OrderArray OrderArray { get; set; }
    }

    }

然后反序列化到您的对象:

XmlSerializer serializer = new XmlSerializer(typeof(GetOrdersResponse ));
using (TextReader reader = new StringReader(xmlResult))
{
    GetOrdersResponse result = (GetOrdersResponse) serializer.Deserialize(reader);
}

int id=result.OrderArray.Orders.First().OrderID; //this will return ID of first object in Orders list.

答案 1 :(得分:2)

你可以这样说:

XDocument xdoc = XDocument.Load("YourXMLFile");
var orderId = xdoc.Descendants("OrderID").FirstOrDefault().Value;

答案 2 :(得分:1)

我不希望xDoc.Elements("GetOrdersResponse")工作,因为这是在默认命名空间中,因为这里的所有内容都在"urn:ebay:apis:eBLBaseComponents"中。因此,您至少需要 才能通过XName告诉它:

    var xDoc = XDocument.Parse(xmlResult);
    XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
    var orderElements = xDoc.Elements(ns + "GetOrdersResponse")
            .Elements(ns + "OrderArray").Elements(ns + "Order");
    foreach (XElement elem in orderElements)
    {
        var orderId = (int)elem.Element(ns + "OrderID");
    }

(注意使用(int)来执行xml特定的转换)

但是,使用XmlSerializer并让 担心解密数据可能会更容易。

答案 3 :(得分:1)

您应该使用此示例代码

重要注意事项

  • 序列化班级标记为[Serializable] attirbute
  • 如果类名与xml根标签不同,则类将为 标记为[XmlRoot(ElementName = "XmlTagName")]属性
  • 如果序列化类将属性类型作为另一个类,则为此 属性标记为[XmlElement("XmlTagName")]属性
  

示例代码

<强>模型

      [Serializable]
        [XmlRoot(ElementName = "HardwareInfo")]
        public class Hardware
        {
            [XmlElement]
            public string cpu_name { get; set; }
            [XmlElement]
            public int ram_size { get; set; }

            [XmlElement("hard_disk")]
            public List<HardDisk> hd { get; set; }                   
        }

        [Serializable]
        [XmlRoot(ElementName = "hard_disk")]
        public class HardDisk
        {
            [XmlElement]
            public string model { get; set; }
            [XmlElement]
            public string size { get; set; }
        }

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlString = @"<HardwareInfo>
                                  <cpu_name> ABC Pentium xyz</cpu_name>
                                  <ram_size> 123 </ram_size>
                                  <hard_disk>
                                    <model>Toshiba XYZ</model>
                                    <size> 123 GB </size>
                                  </hard_disk>
                                  <hard_disk>
                                    <model>Logitech XYZ</model>
                                    <size> 99 GB </size>
                                  </hard_disk>
                                </HardwareInfo>";

            var result = DeSerialization<Hardware>(xmlString);
        }

        static T DeSerialization<T>(string xmlStrig) where T : class
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));                        
            using (StringReader sReader = new StringReader(xmlStrig))
            {
                return (T)xmlSerializer.Deserialize(sReader);
            }
        }
    }          
}

答案 4 :(得分:0)

如果要将xml数据保存在文件

中,也可以使用XmlDocumentXmlNodeList来获取它
        XmlDocument doc = new XmlDocument();
        doc.Load("your XML File Name with extension");
        XmlNodeList elemList = doc.GetElementsByTagName("OrderID");
        for (int i = 0; i < elemList.Count; i++)
        {
            Console.WriteLine(elemList[i].InnerText);
        }