【问题标题】:LINQ to XML extract nested elementsLINQ to XML 提取嵌套元素
【发布时间】:2015-01-16 22:22:31
【问题描述】:

我是 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 的所有人的所有城市和位置!

【问题讨论】:

  • 好的,有什么可以帮忙的吗?
  • 到目前为止你有没有尝试过?
  • 提示:查找所有person元素,过滤到personNumber为2的元素,然后使用Descendants("address")获取地址元素...

标签: c# xml linq


【解决方案1】:

您可以使用 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 
                 };

【讨论】:

  • 比我的回答更简单,可能更有效。
【解决方案2】:

像下面这样的东西应该可以工作:

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" }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多