从XML文件创建节点对

本文关键字:节点 文件创建 XML | 更新日期: 2023-09-27 18:22:19

我有一个带有多文件"OrderInfo"的"OrderList"。每个"订单信息"只有一个"文档代码",最多有四个"文档ID"。如何找到哪个DocumentId属于哪个Documentcode?我有以下xml:

<OrderList>
    <OrderInfo>
        <DocList>
            <DocumentInfo>
                <Documentid>12</Documentid> 
            </DocumentInfo>
            <DocumentInfo>
                <Documentid>22</Documentid> 
            </DocumentInfo>
        </DocList>
        <Documentcode>ABC2</Documentcode> 
   </OrderInfo>
   <OrderInfo>
        <DocList>
            <DocumentInfo>
                <Documentid>11</Documentid> 
            </DocumentInfo>
            <DocumentInfo>
                <Documentid>25</Documentid> 
            </DocumentInfo>
        </DocList>
        <Documentcode>ABC3</Documentcode> 
   </OrderInfo>

带有:

var documentId = myXml.SelectNodes("/OrderList/OrderInfo/DocList/DocumentInfo/Documentid");

我得到了Documentid的总数。但是,我如何在"OrderInfo"中循环并找出对";文档代码"-"DocumentId"?例如:

ABC2=12
ABC2=22
ABC3=11
ABC3=25

如果我有这个,我可以创建字典。

从XML文件创建节点对

我写了这篇Linq的小文章,它可能对丢失的级别/元素没有很强的弹性。

var doc = XElement.Load(fileName);
Dictionary<string, string> dic = doc
     .Descendants("Documentid")
     .ToDictionary(e => e.Value, 
                   e => e.Parent.Parent.Parent.Element("Documentcode").Value );
 // verify
 Console.WriteLine(dic["12"]);
 Console.WriteLine(dic["25"]);