C#确定子元素之一在XElement中是否具有特定值

时间:2018-12-06 10:53:11

标签: c# xml linq lambda xelement

请考虑以下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 个答案:

答案 0 :(得分:1)

使用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);

答案 1 :(得分: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");

答案 2 :(得分:0)

对于VB想要答案的人

    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