Querying an Xml Document for elements using Linq

I am using XDocument to work with XML data. My Xml has the following structure

<Info>
 <ProductDetails>
    <ProductDetail>
      <ProductId>123</ProductId>
      <ProductName>Test</ProductName>
      <ProductType>1</ProductType>
      <AccountDetails>
        <AccountType>Single</AccountType>
        <AccountDetail>
          <AccountId>8564</AccountId>
        </AccountDetail>
      </AccountDetails>
    </ProductDetail>
  </ProductDetails>
</Info>

I want to retrieve the AccountDetails section in the XML based on a particular element Id and then replace it with some other XML content. I tried something like

xdoc.Root.Element("ProductDetails").Element("ProductDetail").Element("ProductId").Value

What will be the best way to achieve this

Jon Skeet
people
quotationmark

It sounds like you want to find the first ProductDetail element with a given product ID. This would do the trick for that:

public XElement FindProduct(XDocument doc, int id)
{
    return doc.Descendants("ProductId")
              .Where(pid => (int) pid == id)
              .Select(pid => pid.Parent)
              .FirstOrDefault();
}

This will return null if it doesn't find the relevant product. Note that it will not detect the presence of multiple products with the same ID.

people

See more on this question at Stackoverflow