0

我是 LINQ to XML 的新手,我在编写 C# 以从 XML 文件中检索多个项目时遇到问题,即在下面的代码示例中。我想浏览文件并检索每个 OrderProduct id=??? 并获取数量和产品中的信息。我只能检索一个订单,但如果文件中有多个订单则不能。

这是我正在使用的 C# 代码,它只检索第一个订单。

xelement = XElement.Load (orderXML);

IEnumerable<XElement> OrderXml = xelement.Elements ();

foreach (var order in OrderXml.Elements ("OrderProducts"))
{
  m_productOrderID = order.Element ("OrderProduct").Attribute ("id").Value;
  m_productName = order.Element ("OrderProduct").Element ("Product").Element ("Name").Value;
  m_productCatalogNumber = order.Element ("OrderProduct").Element ("Product").Element ("CatalogNumber").Value;
  m_productQuantity = order.Element ("OrderProduct").Element ("Quantities").Element ("NumberOfCopies").Value;
}

XML 文件:

<?xml version="1.0" encoding="utf-16"?>
<OrderXml>
  <Order>   
    <OrderProducts>
      <OrderProduct id="569">
        <Quantities>
          <NumberOfRecipients>1</NumberOfRecipients>
          <NumberOfCopies>1</NumberOfCopies>
          <TotalUnits>1</TotalUnits>
        </Quantities>
        <Product id="444">
          <Name>Product 1</Name>
          <CatalogNumber>20130621-001</CatalogNumber>
        </Product>
      </OrderProduct>

      <OrderProduct id="570">
        <Quantities>
          <NumberOfRecipients>1</NumberOfRecipients>
          <NumberOfCopies>100</NumberOfCopies>
          <TotalUnits>100</TotalUnits>
        </Quantities>
        <Product id="258">
          <Name>Product 2</Name>
          <CatalogNumber>20130621-002</CatalogNumber>
        </Product>
      </OrderProduct>
    </OrderProducts>
  </Order>
</OrderXml>
4

1 回答 1

2
from op in xdoc.Descendants("OrderProduct")
let q = op.Element("Quantities")
let p = op.Element("Product")
select new {
   Id = (int)op.Attribute("id"),
   Quantities = new {
       NumberOfRecipients = (int)q.Element("NumberOfRecipients"),
       NumberOfCopies = (int)q.Element("NumberOfCopies"),
       TotalUnits = (int)q.Element("TotalUnits")
   },
   Product = new {
      Id = (int)p.Attribute("id"),
      Name = (string)p.Element("Name"),
      CatalogNumber = (string)p.Element("CatalogNumber")
   }
}

然后获得单订单产品:

var orderProduct = query.FirstOrDefault(x => x.Id == yourId);
if (orderProduct != null)
    // ...

获取所有ID:

var ids = xdoc.Descendants("OrderProduct")
              .Select(op => (int)op.Attribute("id"));

顺便说一句,下次提供您已经拥有的代码

于 2013-08-14T16:20:23.993 回答