[英]Linq to XML — What's wrong with my query
我有这个xml文档(不,我没有组成这个架构)。
<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<wmversion>3</wmversion>
<summary day="362" >
<item key="SomeAttribute">
<item key="1">0.33</item>
<item key="10">3.32</item>
<item key="11">0.23</item>
<item key="12">1.06</item>
<item key="13">0.09</item>
<item key="2">0.35</item>
<item key="3">0.72</item>
<item key="4">0.61</item>
<item key="5">1.01</item>
<item key="6">0.10</item>
<item key="7">0.50</item>
<item key="8">1.27</item>
<item key="9">3.01</item>
</item>
...
现在,我正在尝试查询以下信息:
XDocument doc = XDocument.Load(@"C:\Test.xml");
var q = from d in doc.Descendants("summary")
where d.Element("item").Attribute("key").Value == "SomeAttribute"
select new { LengendKey = d.Attribute("key").Value, ElapsedTime = d.Element("item").Value };
我返回的是0个项目,而不是列表。 有人知道我在做什么错吗?
谢谢,比尔·N
var q = doc.Descendants("summary")
.Where(x => x.Element("item").Attribute("key").Value == "SomeAttribute")
.SelectMany(x => x.Descendants())
.Select( x => new
{ LengendKey = x.Attribute("key").Value, ElapsedTime = x.Value });
这对您有用吗? 还是您在寻找其他东西?
我想还不清楚您要做什么。
var q = from d in doc.Descendants("summary")
where d.Element("item").Attribute("key").Value == "SomeAttribute"
select new { LengendKey = d.Attribute("key").Value, ElapsedTime = d.Element("item").Value }
在这里的代码中, d
是'summary'的所有后代,它们本身具有带有正确属性的'item'元素。
在您发布的XML中,“摘要”只有1个后代,并且没有任何具有正确属性的“项目”子代。
我也对行LengendKey = d.Attribute("key").Value, ElapsedTime = d.Element("item").Value
感到困惑-这里的d
是叶节点(具有键1、2, 3等)-哪个适合语句的第一部分,或者在其下面有'item'元素的父节点-哪个适合语句的第二部分? 不能两者都在同一时间。
你可能想要
// first get the summary; it is a descendant of doc & there's only one.
var summary = doc.Descendants("summary").Single();
// get the element with 'SomeAttribute' from the summary;
// if there's only even going to be one then you can call Single here
var item = summary.Elements().Single(e => e.Name == "item"
&& e.Attribute("key").Value == "SomeAttribute");
var q = item.Elements().Select(e => new
{ LengendKey = e.Attribute("key").Value, ElapsedTime = e.Value });
这有效:
var q = doc.Descendants("summary").Descendants("item").Descendants("item")
.Select ( d => new { LengendKey = d.Attribute("key").Value, ElapsedTime = d.Value });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.