Search code examples
c#xmlsearchxelement

How do I search a XElement with an specific attribute value?


I need to search a child node by a value of one of its attribute, for example say that I have this XML

<Root>
    <Child Name="1" foo="a"/>
    <Child Name="2" foo="a"/>
    <Child Name="3" foo="b"/>
    <Child Name="4" foo="c"/>
    <OhterTag/>
</Root>

I want to extract the node Child with the attribute Name with value 2 . . . I want the full node not just the tag of the node.

I have tried something like this

root.Elements("Attr").Where(child => child.Attribute("Name").Value == "2");

but I have not work


Solution

  • Use the element name, which is "Child" and it should work the way you have it... And since .Where in this case returns an IEnumerable<XElement>, to get just that Element, use .First() at the end.

    root.Elements("Child")
        .Where(child => child.Attribute("Name").Value == "2")
        .First()
    

    ... or you can just use the predicate with .First()

    root.Elements("Child")
        .First(child => child.Attribute("Name").Value == "2")
    

    Finally you can use .FirstOrDefault() in case the node doesn't exist, to avoid null reference exceptions, as per discussion in below comments, suggested by @HamletHakobyan

    root.Elements("Child")
        .FirstOrDefault(child => child.Attribute("Name").Value == "2")