使用 Linq 解析 XML 时,仅获取一个对象
我正在尝试使用以下 xml: 填充一个数组:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<data>
<item>
<date>1307018090</date>
<price>10.4718867</price>
<low>10.38100000</low>
<high>10.49000000</high>
<nicedate>14:39</nicedate>
</item>
<item>
...
</item>
等等,
我正在使用此 Linq 查询,这对我来说意味着它将为每个创建一个对象:
var items = from item in doc.Element("data").Descendants()
select new Currency
{
Close = item.Element("price").Value.ToString(),
Date = item.Element("date").Value.ToString(),
Low = item.Element("low").Value.ToString(),
High = item.Element("high").Value.ToString(),
Time = item.Element("nicedate").Value.ToString()
};
当我遍历项目时,只会选择一个项目。我不太习惯 Linq,所以我不知道如何正确构造这个语句。有什么建议吗?
I'm trying to populate an array with the following xml:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<data>
<item>
<date>1307018090</date>
<price>10.4718867</price>
<low>10.38100000</low>
<high>10.49000000</high>
<nicedate>14:39</nicedate>
</item>
<item>
...
</item>
and so on
I'm using this Linq-query, which to me means that It'll create one object per :
var items = from item in doc.Element("data").Descendants()
select new Currency
{
Close = item.Element("price").Value.ToString(),
Date = item.Element("date").Value.ToString(),
Low = item.Element("low").Value.ToString(),
High = item.Element("high").Value.ToString(),
Time = item.Element("nicedate").Value.ToString()
};
And when I foreach through items, only one item gets selected. I'm not very used to Linq so I can't figure out how to properly construct this statement. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要像这样启动 Linq-Xml
You need to start the Linq-Xml like so
Desedants()
方法不仅返回子项,还返回孙子项、孙孙子项等。因此,LINQ 处理的第二个标记是您的第一个
并且它没有被处理(我认为这里应该有一个例外,目前无法检查)。按照 @DaveShaw 的建议,将
Descendants()
调用替换为Elements("item")
Descedants()
method returns not only children, but also grand-children, grand-grand-children etc. So, the second tag that gets processed by LINQ is your first<item>
's<date>
and it isn't processed (I think there should be an exception here, can't check at the moment).Replace your
Descedants()
call toElements("item")
, as suggested by @DaveShaw