给出以下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”中寻找值。
答案 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();