选择子元素具有值的XElement

时间:2013-03-04 10:24:40

标签: c# linq linq-to-xml

给出以下XML:

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

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

我到目前为止:

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

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

1 个答案:

答案 0 :(得分:13)

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

或使用XElement转换为int

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