0

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

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Arian
  • 12,793
  • 66
  • 176
  • 300

3 Answers3

1

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);
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Thanks, Now How can I chack if `c4` has value 1 with `Lambda` – Arian Dec 06 '18 at 11:04
  • like : `var nodes = Doc.Descendants().Where(x=> x.Name == "c4" && x.Value == "1");` if this returns any object then it's found otherwise not, you can check then `if(nodes.Any()) { // c4 has value 1}` – Ehsan Sajjad Dec 06 '18 at 11:05
1
string x = @"<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>";
XElement xml = XElement.Parse(x);
bool has_one = xml.Elements().Any(z => z.Value == "1");
JohnyL
  • 6,894
  • 3
  • 22
  • 41
0

For VB'ers wanting an answer

    Dim xe As XElement
    'xe = XElement.Load("URI here")

    'for testing use literals
    xe = <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>

    'any child = 1
    Dim ie As IEnumerable(Of XElement) = From el In xe.Elements Where el.Value = "1" Select el

    'check c4 for 1
    ie = From el In xe.<c4> Where el.Value = "1" Select el
    'or
    If xe.<c4>.Value = "1" Then
        '
    End If
dbasnett
  • 11,334
  • 2
  • 25
  • 33