简体   繁体   English

当子节点同名时如何从XML序列化到C#.net

[英]How to serialize from XML to C#.net when child node are same name

This is the file structure: 这是文件结构:

<BODY>
    <IMPORTDATA>
            <REQUESTDATA>
                <TALLYMESSAGE xmlns:UDF="TallyUDF">
                    <VOUCHER REMOTEID="abcd1" VCHKEY="0000a582:000000e0" VCHTYPE="Payment" ACTION="Create" OBJVIEW="Accounting Voucher View">
                        <ALLLEDGERENTRIES.LIST>
                            <LEDGERNAME>Bank Charges</LEDGERNAME>
                            <AMOUNT>-575.00</AMOUNT>
                        </ALLLEDGERENTRIES.LIST>
                        <ALLLEDGERENTRIES.LIST>
                            <LEDGERNAME>Standard Chartered Bank Ltd-01-5547520-01</LEDGERNAME>
                            <AMOUNT>575.00</AMOUNT>
                        </ALLLEDGERENTRIES.LIST>
                    </VOUCHER>
                </TALLYMESSAGE>
            </REQUESTDATA>
        </IMPORTDATA>
    </BODY>

Here there are two ALLLEDGERENTRIES.LIST 's. 这里有两个ALLLEDGERENTRIES.LIST How do I find the value of LEDGERNAME of these two ALLLEDGERENTRIES.LIST 's? 如何找到这两个ALLLEDGERENTRIES.LISTLEDGERNAME的值? I detect the node this way 我这样检测节点

XmlNodeList dataNodes = xmlDoc.SelectNodes("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER")

You can use little-bid more friendly API for working with xml - LINQ to XML 您可以使用低价竞标更友好的API来处理xml- LINQ to XML

var doc = XDocument.Load(PathToXmlFile);

var ledgerNames = doc.Root
                     .Descendants("ALLLEDGERENTRIES.LIST")
                     .Elements("LEDGERNAME")
                     .Select(element => element.Value);

foreach (var name in ledgerNames)
{
    Console.WriteLine(name);
}

Descendants will return all xml elements with given name existed in xml file on any level. Descendants将返回任何级别的xml文件中存在的具有给定名称的所有xml元素。 From MSDN 从MSDN

So basically you can use Descendants straight for LEDGERNAME elements and omit Root too. 因此,基本上,您可以将Descendants直接用于LEDGERNAME元素,也可以省略Root

var ledgerNames = doc.Descendants("LEDGERNAME")
                     .Select(element => element.Value);

Copy the XML (mark all and click ctrl + c). 复制XML(标记全部并单击ctrl + c)。 In visual studio go to 在Visual Studio中转到

Edit > Past Special > Past XML As Classes 编辑>过去的特殊情况>过去的XML作为类

This will create the XML structure as C# classes. 这将创建XML结构作为C#类。 ALLLEDGERENTRIES.LIST will be presented as an array. ALLLEDGERENTRIES.LIST将作为数组显示。

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

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