简体   繁体   English

Linq查询-将嵌套的XML读取到字典中

[英]Linq query - reading nested XML to dictionary

I am trying to parse nested XML file 我正在尝试解析嵌套的XML文件

The structure is (simplified) following: 结构(简化)如下:

<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>

I need to make a dictionary of all parts ID and their corresponding car id (CID), ie 我需要制作所有零件ID及其对应的汽车ID(CID)的字典,即

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM