如何构造更复杂的单个 LINQ to XML 查询?
我是一个 LINQ 新手,所以一旦回答了下面的问题,它可能会变得非常简单和明显,但我不得不承认这个问题让我很恼火。
给定此 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>
我可以使用以下 LINQ to XML 查询千克和美英担之间的转换系数的值,但肯定有办法将四个连续查询压缩为单个复杂查询吗?
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"));
}
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"));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可行,只需将它们添加在一起即可:
This would work, just add them together: