代码之家  ›  专栏  ›  技术社区  ›  DooDoo

C确定某个子元素在Xelement中是否具有特定值

  •  0
  • DooDoo  · 技术社区  · 6 年前

    请考虑这个 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>
    

    如何编写lambda表达式以查找 MyRoot 它的价值是1?

    谢谢

    3 回复  |  直到 6 年前
        1
  •  1
  •   Ehsan Sajjad    6 年前

    这是非常简单的使用 XDocument 类和一些Linq,它们是:

    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

    与lambda:

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

    现在您可以迭代它:

    foreach(var node in nodes)
          Console.WriteLine(node.Name + ":  " + node.Value);
    
        2
  •  1
  •   JohnyL    6 年前
    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");
    
        3
  •  0
  •   dbasnett    6 年前

    对于想要答案的vb'ers

        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