LINQ to XML提取嵌套元素

时间:2015-01-16 13:49:13

标签: c# xml linq

我是LINQ和XML解析的新手,而不是C#编程的新手。对于以下XML结构,我试图提取嵌套元素:

  <persons>
    <person>
      <personNumber>2</personNumber>
      <info>free text</info>
      <addresses>
        <address>
          <city>XXX</city>
          <location>1</location>
        </address>
        <address>
          <city>YYY</city>
          <location>2</location>
        </address>
      </addresses>
    </person>
    <person>
      <personNumber>3</personNumber>
      <info>free text</info>
      <addresses>
        <address>
          <city>XXX</city>
          <location>1</location>
        </address>
        <address>
          <city>YYY</city>
          <location>2</location>
        </address>
      </addresses>
    </person>
  </persons>

我希望能够为personNumber = 2的所有人取得所有城市和位置!

2 个答案:

答案 0 :(得分:2)

你可以用linq这样做:

var result = from p in xmlDoc.Descendants("person")
             from a in p.Descendants("address")
             where p.Element("personNumber").Value == "2" 
             select new 
                 { 
                   City = a.Element("city").Value, 
                   Location = a.Element("location").Value 
                 };

答案 1 :(得分:1)

如下所示:

XDocument xmlDoc = XDocument.Load(@"mypath\persons.xml");

var q = from e in xmlDoc.Descendants("person")
        where e.Element("personNumber").Value == "2"
        let address = e.Descendants("address")
        from a in address
        select new {
           city = a.Element("city").Value,
           location = a.Element("location").Value
        };

使用OP中提供的示例xml,上面的linq查询产生以下结果:

[0] = { city = "XXX", location = "1" }
[1] = { city = "YYY", location = "2" }