2
votes

I have below xml file:

<PackList>
  <Header>
    <OrderNumber>PO12123</OrderNumber>
    <OrderQty>100</OrderQty>
  </Header>
  <Items>
    <Item>
      <PN>31023312</PN>
      <Color>Black</Color>
    </Item>
    <Item>
      <PN>22023312</PN>
      <Color>White</Color>
    </Item>
    <Item>
      <PN>44023312</PN>
      <Color>Blue</Color>
    </Item>
  </Items>
</PackList>

I'm able to read the Header part using below code:

public class OrderItem
{
    public string PN { get; set; }
    public string Color { get; set; }
}

public class PList
{
    public string OrderNumber { get; set; }
    public int OrderQty { get; set; }
    public List<OrderItem> OrderItems = new List<OrderItem>();
}

(...)
PList PL = new PList();
using (XmlReader reader = XmlReader.Create(@"c:/Test/PackList.xml"))
{
    reader.ReadToFollowing("OrderNumber");
    PList.OrderNumber = reader.ReadElementContentAsString();
    reader.ReadToFollowing("OrderQty");
    PList.OrderQty = reader.ReadElementContentAsInt();
}
(...)

But I have no idea on how to read every Item within the Items tag.

Any advice?

3
Linq (from Xml to DTO) is much easier than XmlReader. Is the source document huge? Or can you load the whole xml into memory? If so, see this post : stackoverflow.com/questions/18498467/… - granadaCoder
I use like my answer following posting. I use a combination of XmlReader and Xml Linq. stackoverflow.com/questions/37503602/efficient-parsing-of-xml/… - jdweng

3 Answers

1
votes

Use XmlNodeList

XmlDocument document = new XmlDocument();

document.Load(@"c:/Test/PackList.xml");

XmlNodeList Items = document.GetElementsByTagName("Item");

foreach (XmlNode item in Items)
{
    // do something
}
1
votes

Check out XmlReader.ReadSubtree() method.

Returns a new XmlReader instance that can be used to read the current node, and all its descendants.

https://msdn.microsoft.com/en-us/library/system.xml.xmlreader.readsubtree(v=vs.110).aspx

Note : Position of main reader might be also be moved, so you will continue at not exactly the position you were ReadToFollowing() got you.

1
votes
reader.ReadToFollowing("OrderNumber");
plist.OrderNumber = reader.ReadElementContentAsString();
reader.ReadToFollowing("OrderQty");
plist.OrderQty = reader.ReadElementContentAsInt();

reader.ReadToFollowing("Items");

using (var innerReader = reader.ReadSubtree())
{
    while (innerReader.ReadToFollowing("PN"))
    {
        var item = new OrderItem();
        item.PN = innerReader.ReadElementContentAsString();
        reader.ReadToFollowing("Color");
        item.Color = innerReader.ReadElementContentAsString();

        plist.OrderItems.Add(item);
    }
}

reader.ReadToFollowing("foo");
var foo = reader.ReadElementContentAsString();

Where foo is tag name after the Items.

Don't forget plist.OrderItems = new List<OrderItem>();