繁体   English   中英

LINQ to XML:选择以其他值为条件的值

[英]LINQ to XML: Select values conditional on other values

在下面的XML示例中,可以有许多“元素”条目。 对于每个“元素”,只能有一个“系统”条目,但是在同一“元素”内的“系统”条目旁边可以有许多“设备”条目。

我想为每个“元素”知道如何在C#中构造一个LINQ to XML查询,该查询可以选择数据,如下所示:

对于每个“元素”,其中“系统”包含“ 1A7”,仅返回那些也具有“设备”-“ InfoB”-“设置”-“名称”值的值FALSE的“设备”-“ InfoA”-“核心”值,然后将那些匹配的值放入列表中。

在过去的一周中,LINQ对我来说非常困难。 我还没有发布代码段,因为我认为经过(失败)的大量代码段都不能比上面的查询概述更清楚地说明这个问题。 我非常感谢您提供的帮助,并且希望上面的查询对于此处的LINQ to XML专家来说非常简单。

XML:

<?xml version="1.0" standalone="yes" ?>
<Base_TP>
  <Element>
    <System>
      <id>341A7</id>
    </System>
    <Device>
      <InfoA>
        <id>12</id>
        <Core>TRUE</Core>
      </InfoA>
      <InfoB>
        <Settings>
          <type>0</type>
          <name>DeviceA</name>
        </Settings>
      </InfoB>
    </Device>
    <Device>
      <InfoA>
        <id>13</id>
        <Core>FALSE</Core>
      </InfoA>
      <InfoB>
        <Settings>
          <type>0</type>
          <name>DeviceB</name>
        </Settings>
      </InfoB>
    </Device>
    <Device>
      <InfoA>
        <id>14</id>
        <Core>FALSE</Core>
      </InfoA>
      <InfoB>
        <Settings>
          <type>0</type>
          <name>DeviceC</name>
        </Settings>
      </InfoB>
    </Device>
  </Element>
</Base_TP>
var doc = XDocument.Load("Input.xml");

var values = from e in doc.Root.Elements("Element")
             where ((string)e.Element("System").Element("id")).Contains("1A7")
             from d in e.Elements("Device")
             where !(bool)d.Element("InfoA").Element("Core")
             select (string)d.Element("InfoB").Element("Settings").Element("name");

返回IEnumerable<string> 对其调用ToString以获得具有实现结果的List<string>

XDocument xDoc = XDocument.Load("System.xml"); 
List<string> result = xDoc.Descendants("Element").Where(el => el.Element("System").Element("id").Value.Contains("1A7")).SelectMany(e => e.Descendants("Device").Where(d => d.Element("InfoA").Element("Core").Value.ToUpper() == "FALSE").Select(x => x.Element("InfoB").Element("Settings").Element("name").Value)).ToList();

我将在Visual Basic中执行此操作,因为它具有对xml内联的本机支持,但翻译非常简单。

Dim elements = From e In xml...<Element>
               Where e.<System>.<Id>.Value.Contains("1A7")
               Select e
Dim deviceBs = (From e In elements
               Where e.<Device>.<InfoA>.<Core>.Value = "FALSE"
               Select e.<Device>.<InfoB>.<name>.Value).ToList

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM