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:

<Agents>
    <Agent ID="xxx">
        <Login>xxx</Login>
        <Password>xxxx</Password>
        <Products>
            <Product ID="zzz">
            </Product>
        </Products>
    </Agent>
</Agents>

Here is my first attempt at a LINQ query:

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

Thanks.

,

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

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

Leave a Comment