How do I construct a more complex single LINQ to XML query?
Posted
by Cyberherbalist
on Stack Overflow
See other posts from Stack Overflow
or by Cyberherbalist
Published on 2010-06-02T12:08:53Z
Indexed on
2010/06/02
12:14 UTC
Read the original article
Hit count: 294
c#
|linq-to-xml
I'm a LINQ newbie, so the following might turn out to be very simple and obvious once it's answered, but I have to admit that the question is kicking my arse.
Given this XML:
<measuresystems>
<measuresystem name="SI" attitude="proud">
<dimension name="mass" dim="M" degree="1">
<unit name="kilogram" symbol="kg">
<factor name="hundredweight" foreignsystem="US" value="45.359237" />
<factor name="hundredweight" foreignsystem="Imperial" value="50.80234544" />
</unit>
</dimension>
</measuresystem>
</measuresystems>
I can query for the value of the conversion factor between kilogram and US hundredweight using the following LINQ to XML, but surely there is a way to condense the four successive queries into a single complex query?
XElement mss = XElement.Load(fileName);
IEnumerable<XElement> ms =
from el in mss.Elements("measuresystem")
where (string)el.Attribute("name") == "SI"
select el;
IEnumerable<XElement> dim =
from e2 in ms.Elements("dimension")
where (string)e2.Attribute("name") == "mass"
select e2;
IEnumerable<XElement> unit =
from e3 in dim.Elements("unit")
where (string)e3.Attribute("name") == "kilogram"
select e3;
IEnumerable<XElement> factor =
from e4 in unit.Elements("factor")
where (string)e4.Attribute("name") == "pound"
&& (string)e4.Attribute("foreignsystem") == "US"
select e4;
foreach (XElement ex in factor)
{
Console.WriteLine ((string)ex.Attribute("value"));
}
© Stack Overflow or respective owner