【问题标题】:Select XElement where child element has a value选择子元素有值的 XElement
【发布时间】:2013-03-04 10:24:39
【问题描述】:

给定以下 XML:

<platforms>
  <platform>
    <id>1</id>
    <price>2.99</price>
  </platform>
</platforms>

如何根据值为“1”的子元素“id”选择“平台”元素作为 XElement 对象?

我已经走到这一步了:

XDocument xPlatformXml = new XDocument();
XElement xel = xPlatformXml.Element("platforms").Elements("platform").Where(x => x.Value == "1").SingleOrDefault();

但这是在“平台”元素而不是“id”中寻找值。

【问题讨论】:

    标签: c# linq linq-to-xml


    【解决方案1】:
    XDocument xPlatformXml = new XDocument();
    XElement xel = xPlatformXml.Element("platforms")
                               .Elements("platform")
                               .Where(x => x.Element("id").Value == "1")
                               .SingleOrDefault();
    

    或者使用XElementint的转换:

    XDocument xPlatformXml = new XDocument();
    XElement xel = xPlatformXml.Element("platforms")
                               .Elements("platform")
                               .Where(x => (int)x.Element("id") == 1)
                               .SingleOrDefault();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-27
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2015-04-03
      • 2011-05-15
      • 1970-01-01
      • 2013-07-17
      相关资源
      最近更新 更多