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?
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>();