简体   繁体   English

如何使用嵌套数组元素反序列化XML?

[英]How to deserialize an XML with a nested array elements?

Deserialization of XML file with nested array of elements 具有嵌套元素数组的XML文件的反序列​​化

I've searched but can't see any helpful examples. 我已经搜索过,但看不到任何有用的示例。

this is my XML sample: 这是我的XML示例:

<trans>
  <orderNo>0001</orderNo>
  <orderDate>08/07/2014</orderDate>
  <orders>
    <item>
      <itemName>item1</itemName>
      <itemAmount>200</itemAmount>
      <itemMeasures>
        <measure>each</measure>
        <measure>case</measure>
      </itemMeasures>
    </item>
    <item>
      <itemName>item2</itemName>
      <itemAmount>100</itemAmount>
      <itemMeasures>
        <measure>each</measure>
        <measure>case</measure>
      </itemMeasures>
    </item>
  </orders>
</trans>

You must create classes for each of the structures you have in the XML and then using XmlSerializer and the method Deserialize of the object from that class you can create nested arrays with the values. 您必须为XML中具有的每个结构创建类,然后使用XmlSerializer和该类中对象的反序列化方法才能使用值创建嵌套数组。 If you want code and example, please edit your post with the full xml structure. 如果您需要代码和示例,请使用完整的xml结构编辑您的帖子。 See the example below for part of your xml: 请参阅以下示例,了解您的xml的一部分:

[XmlType("trans")]
public class Trans
{
    [XmlElement("orderNo")]
    public string OrderNo { get; set; }

    [XmlElement("orderDate")]
    public string OrderDate { get; set; }

    [XmlArray("orders")]
    public HashSet<Item> Orders { get; set; }
}

[XmlType("item")]
public class Item
{
    [XmlElement("itemName")]
    public string ItemName { get; set; }

    [XmlElement("itemAmount")]
    public string ItemAmount { get; set; }
}

The the Deserialization code is: 反序列化代码为:

XmlSerializer mySerializer = new XmlSerializer(typeof(Trans[]), new XmlRootAttribute("trans"));
using (FileStream myFileStream = new FileStream("XmlFile.xml", FileMode.Open))
{
    Trans[] r;
    r = (Trans[])mySerializer.Deserialize(myFileStream);
}

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

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