UltraJ
UltraJ

Reputation: 487

Retrieving Multiple Items from an XML File using LINQ to XML with C#

I'm new to LINQ to XML and I'm having problems writing C# to retrieve multiple items from an XML file, i.e. in the code sample below. I would like to go through the file and retrieve each OrderProduct id=??? and get the information in Quantities and Product. I can retrieve a single order only, but not if more than one is in the file.

This is the C# code I'm using which only retrieves the first order.

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;
}

The XML file:

<?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>

Upvotes: 0

Views: 633

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

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")
   }
}

Then getting single order product:

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

Getting all ids:

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

BTW Next time provide code which you already have

Upvotes: 2

Related Questions