2

我知道这可能比我做的要容易得多。我能够将所有机器从 XElement 中拉出,但我试图弄清楚如何拉出具有特定序列号的机器。在下面的 XML 片段中,我想使用序列 = 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

4 回答 4

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");
于 2013-03-02T06:23:56.287 回答
1

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

XmlNodeList nodeList = root.SelectNodes("descendant::Location[Sequence='1']");
于 2013-03-02T06:22:45.540 回答
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);
    }
}
于 2013-03-02T08:09:49.887 回答
0

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

    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 的值,

于 2013-03-02T10:43:45.297 回答