选择子元素有值的XElement

本文关键字:XElement 元素 选择 | 更新日期: 2023-09-27 18:01:58

给定以下XML:

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

如何根据子元素"id"的值为"1"选择"platform"元素作为XElement对象?

我已经走到这一步了:

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

但是这是在寻找"platform"元素中的值而不是"id"

选择子元素有值的XElement

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();