Linq查询-将嵌套的XML读取到字典中 [英] Linq query - reading nested XML to dictionary
本文介绍了Linq查询-将嵌套的XML读取到字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试解析嵌套的XML文件
I am trying to parse nested XML file
结构(简化)如下:
<CARS_LIST_OUTPUT>
<RESPONSE>
<DATETIME>2014-09-03T12:12:55Z</DATETIME>
<CARS_LIST>
<CAR>
<CID>12123</CID>
<PARTS_LIST>
<PART>
<ID>QWEDS23</ID>
</PART>
<PART>
<ID>QWEDS26</ID>
</PART>
</PARTS_LIST>
</CAR>
<CAR>
<CID>44123</CID>
<PARTS_LIST>
<PART>
<ID>QWED101</ID>
</PART>
<PART>
<ID>QAADS23</ID>
</PART>
</PARTS_LIST>
</CAR>
</CARS_LIST>
</RESPONSE>
<CAR_LIST_OUTPUT>
我需要制作一个包含所有部件ID及其对应的汽车ID(CID)的字典,即
I need to make a dictionary of all parts ID and their corresponding car id (CID), i.e.
QWEDS23,12123 QWEDS26,12123 QWED101、44123 QAADS23,44123
QWEDS23, 12123 QWEDS26, 12123 QWED101, 44123 QAADS23, 44123
到目前为止,我到了这一点:
So far I got to this point:
var nodes =
from c in carDirectory.Descendants("CAR")
select new
{
parts = c.Descendants("PART")
.Select(part => new {
ID = part.Element("ID").Value,
c.Element("CID").Value
}).ToDictionary(r => r.ID)
};
但这会产生一个词典列表.是否有可能实现我所需要的?如果是,我该如何改善解决方案?谢谢你的想法!
But this results in a list of dictionaries. Is it possible to achieve what I need? If yes, how can I improve my solution? Thank you for ideas!
推荐答案
这种方法应该可以解决问题:
Something like this should do the trick:
carDirectory.Descendants("CAR")
.SelectMany(x => x.Descendants("ID")
.Select(e => new KeyValuePair<string, string>(
(string) e,
(string) x.Element("CID"))))
.ToDictionary(x => x.Key, x => x.Value);
这篇关于Linq查询-将嵌套的XML读取到字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文