Search code examples
c#xmllinqlambdaxelement

C# determine if one of child elements has specific value in XElement


Please consider this XML:

<MyRoot>
    <c1>0</c1>
    <c2>0</c2>
    <c3>0</c3>
    <c4>0</c4>
    <c5>1</c5>
    <c6>0</c6>
    <c7>0</c7>
    <c8>0</c8>
</MyRoot>

How can I write a lambda expression to find if one of child of MyRoot has 1 for it's value?

Thanks


Solution

  • This is pretty trivial using XDocument class and some linq which would be :

    string xml=@"<MyRoot>
        <c1>0</c1>
        <c2>0</c2>
        <c3>0</c3>
        <c4>0</c4>
        <c5>1</c5>
        <c6>0</c6>
        <c7>0</c7>
        <c8>0</c8>
    </MyRoot>";
    
         XDocument Doc = XDocument.Parse(xml);
         var nodes = from response in Doc.Descendants()
                     where response.Value == "1" 
                     select new {Name = response.Name, Value = response.Value };
    
        foreach(var node in nodes)
              Console.WriteLine(node.Name + ":  " + node.Value);
    

    See the working DEMO Fiddle as example

    with lambda:

    var nodes = Doc.Descendants().Where(x=> x.Value == "1")
                               .Select(x=> {Name = x.Name, Value = x.Value });
    

    Now you can iterate it:

    foreach(var node in nodes)
          Console.WriteLine(node.Name + ":  " + node.Value);