c# – LINQ to XML – Get element based on a nested elements value – Education Career Blog

I want to select an element within my XML based on the value of a nest element.

Here is an example of the XML:

    <Agent ID="xxx">
            <Product ID="zzz">

Here is my first attempt at a LINQ query:

var DetailsOfUserAccount =
  from agent in policySpecificationXml
        .FirstOrDefault(p => (string)p.Attribute("ID") == productId)
  select new



Not entirely clear, but sounds like you want something like…

var detailsOfUserAccount = policySpecificationXml
    .Where(agent => agent.Descandants("Product")
                         .Any(product => (string)product.Attribute("ID")
                                             == productId))

Leave a Comment