0

Deserialization of XML file with nested array of elements

I've searched but can't see any helpful examples.

this is my XML sample:

<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>
2
  • how do your model classes look like? Commented Aug 7, 2014 at 12:49
  • 2
    I've searched but can't see any helpful examples Hard to believe. One of the mostly covered topics Commented Aug 7, 2014 at 12:51

1 Answer 1

3

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. If you want code and example, please edit your post with the full xml structure. See the example below for part of your 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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.