Linq to XML -- What's wrong with my query
I have this xml document (and no I didn't make up this schema).
<?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">开发者_StackOverflow中文版;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>
...
Now I'm trying to query this information like:
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 };
I'm returning 0 items instead of the list. Does anyone know what i'm doing wrong here?
Thanks, Bill N
I guess it's not really clear what you are trying to do.
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 }
In your code here, d
is all the descendents of 'summary' which themselves have an 'item' element with the correct attribute.
In the XML you've posted, there's only 1 descendent of 'summary', and it doesn't have any 'item' children with the correct attribute.
I'm also confused about the line LengendKey = d.Attribute("key").Value, ElapsedTime = d.Element("item").Value
- is d
here supposed to the leaf node (which has key 1, 2, 3 etc) - which would fit the first part of the statement, or the parent node which has the 'item' elements underneath it - which fits the second part of the statement? It can't be both at the same time.
You probably want
// 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")
.Where(x => x.Element("item").Attribute("key").Value == "SomeAttribute")
.SelectMany(x => x.Descendants())
.Select( x => new
{ LengendKey = x.Attribute("key").Value, ElapsedTime = x.Value });
Does this work for you ? Or Are you looking for something else ?
This works:
var q = doc.Descendants("summary").Descendants("item").Descendants("item")
.Select ( d => new { LengendKey = d.Attribute("key").Value, ElapsedTime = d.Value });
精彩评论