通过内部元素查询特定数据的最佳方法是什么?

时间:2013-03-02 05:56:10

标签: c# xml linq linq-to-xml

我知道这可能比我做起来容易得多。我能够从XElement中取出所有机器,但我正在试图找出如何拔出具有特定序列号的机器。在下面的XML片段中,我想使用sequence = 1的机器。

XML:

<Location>
  <Sequence>1</Sequence>
  <Machines>
    <Machine></Machine>
    <Machine></Machine>
  </Machines>
</Location>
<Location>
  <Sequence>2</Sequence>
  <Machines>
    <Machine></Machine>
    <Machine></Machine>
  </Machines>
</Location>

代码:

IEnumerable<XElement> locSeqMachines = 
                      from seq in LocationRows.Descendants("Location")
                      select seq;

var eMachines = locSeqMachines.Descendants("Machine");
foreach (var machine in eMachines)
{   
}

4 个答案:

答案 0 :(得分:2)

这样的事情应该可以胜任:

int soughtId = 1; // Assuming this is coming from somewhere
string soughtIdStr = soughtId.ToString();
var machines = LocationRows.Descendants("Location")
                           .Where(l => (string)l.Element("Sequence") == 
                                       soughtIdStr)
                           .Descendants("Machine");

答案 1 :(得分:1)

您可以使用XPath按特定顺序选择节点:

XmlNodeList nodeList = root.SelectNodes("descendant::Location[Sequence='1']");

答案 2 :(得分:1)

此代码将对按位置序列值过滤的位置标记中的所有计算机数据进行分组:

var locSeqMachines = from seq in LocationRows.Descendants("Location")
                     where seq.Element("Sequence").Value == "1"
                     select new {
                         Sequence = seq.Element("Sequence").Value,
                         Machines = from m in seq.Descendants("Machines").Elements()
                                    select m.Value
                     };

以下是一些代码,演示了如何访问数据(以及测试代码段):

foreach (var location in locSeqMachines) {
    Console.WriteLine("sequence: {0}", location.Sequence);
    foreach (var machine in location.Machines) {
        Console.WriteLine(" machine: {0}", machine);
    }
}

答案 3 :(得分:0)

在解析给定的xml时,您可以使用this方法获得答案而不会引发多个根元素的错误。

    var xmlText =   @"<root>
                       <Location>
                        <Sequence>1</Sequence>
                        <Machines>
                          <Machine></Machine>
                          <Machine></Machine>
                        </Machines>
                       </Location>
                       <Location>
                        <Sequence>2</Sequence>
                        <Machines>
                          <Machine></Machine>
                          <Machine></Machine>
                         </Machines>
                       </Location>
                      </root>";

    var elements     = XElement.Parse(xmlText);
    var machineWith1 = from subElem in elements.Elements("Location")
                           where subElem.Element("Sequence").Value == "1"
                           select subElem.Element("Machines").Elements("Machine");

然后你可以检查machineWith1的值,