【问题标题】:C# determine if one of child elements has specific value in XElementC# 确定子元素之一是否在 XElement 中具有特定值
【发布时间】:2018-12-06 10:53:11
【问题描述】:

请考虑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?

谢谢

【问题讨论】:

  • @dymanoid 根据帖子主题,我猜他的“id”是指节点的值...
  • @dymanoid 错误抱歉。已更新
  • 请在发布前验证问题,xml 格式错误,即无效 xml
  • 你尝试实现有什么问题以及为什么这里必须使用 lambda 表达式?

标签: c# xml linq lambda xelement


【解决方案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);

【讨论】:

  • 谢谢,如果c4Lambda 的值为1,我该如何破解
  • like : var nodes = Doc.Descendants().Where(x=&gt; x.Name == "c4" &amp;&amp; x.Value == "1"); 如果这返回任何对象,那么它没有找到,否则你可以检查然后if(nodes.Any()) { // c4 has value 1}
【解决方案2】:
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】:

    对于想要答案的 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
    

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      相关资源
      最近更新 更多