C#:XML 解析:在节点上分组 XML,然后在同一组下分组

C# : XML Parsing : Group XML on a node and then subGroup underneath the same group

<?xml version="1.0" encoding="UTF-8"?>
<Batch Id="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PurchaseOrders>
    <PurchaseOrder id="xx267681">
      <Header>
        <AccountNumber>999</AccountNumber>
        <ShipDate>2/10/2009</ShipDate>
      </Header>
      <PurchaseOrderDetails>
        <Item>
          <ItemNumber>yy235240</ItemNumber>
          <Quantity>200</Quantity>
        </Item>
        <Item>
          <ItemNumber>yy336820</ItemNumber>
          <Quantity>3</Quantity>
        </Item>
      </PurchaseOrderDetails>

    </PurchaseOrder>
    <PurchaseOrder id="zz267456">
      <Header>
        <AccountNumber>123</AccountNumber>
        <ShipDate>2/10/2009</ShipDate>
      </Header>
      <PurchaseOrderDetails>
        <Item>
          <ItemNumber>nn235240</ItemNumber>
          <Quantity>200</Quantity>
        </Item>
      </PurchaseOrderDetails>
    </PurchaseOrder>
  </PurchaseOrders>
</Batch>

上面附上的是我要解析的 XML 文件。我当前的 C# 代码查找 XML 文件中的所有项目并将其分配给 PO#。但是最近的 XML 文件我知道在同一个 XML 文件中可以有多个 PO#,因此我现在只需要找到与该 PO# 匹配的那些项目。 所以在上面的例子中,带有 xx267681 的 PONumber 有 2 个项目,而第二个采购订单只有项目。

这是我到目前为止尝试过的方法。

        try
            { 
                ArrayList ItemsInFeed = new ArrayList();
                XDocument xDoc = XDocument.Load(fileName);
                foreach (var node in xDoc.Descendants("PurchaseOrder"))
                {
                    poID = node.Attribute("id").Value;  
                }
                foreach (var node in xDoc.Descendants("Item"))
                {
                    Items itemRcd = new Items();
                    itemRcd.ItemNr = node.Descendants("ItemNumber")?.First().Value;
                    ItemsInFeed.Add(itemRcd);
                }

                if (ItemsInFeed.Count > 0)
                {
        // Do other logic based on the items linked to each PO#.
        // Issue found : So far each XML file has one PO#, but latest XML file received has more than PO# and underlying items.
        ItemsInFeed.Clear();
                }
            }
            catch (Exception ex)
            {
                //Catch exception here 
            }

尝试以下操作:

           XDocument xDoc = XDocument.Load(fileName);

            var results = xDoc.Descendants("PurchaseOrder").Select(x => new
            {
                poID = (string)x.Attribute("id"),
                items = x.Descendants("Item").Select(y => new
                {
                    itemNumber = (string)y.Element("ItemNumber"),
                    quantity = (int)y.Element("Quantity")
                }).ToList()
            }).ToList();