简体   繁体   中英

Serialize Class with List<> to XML

I am quite new to XML. I want to serialize a class to produce below output using XMLSerializer:

<?xml version="1.0" encoding="UTF-8"?>
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="DBK100.xsd">
<header>
    <return-code>DBK100</return-code> 
    <return-desc>Daily Net Open Position</return-desc>
    <inst-code> </inst-code>
    <inst-name> </inst-name>
    <as-at-date> </as-at-date>
</header>
<body>
    <return-data>
        <item-code>10010</item-code>
        <position-component>1. Net Assets</position-component>
        <us-dollar>
            <amount>23423</amount>
            <nature-of-position>vxgfxdfd</nature-of-position>
        </us-dollar>
        <gbp>
            <amount></amount>
            <nature-of-position></nature-of-position>
        </gbp>
    </return-data>
</body>
</return>

1.Please Add using System.Xml as a reference; 2.Make a class named Item in this way

     public class Item
            {
                public string itemCode { get; set; }
                public string positionComponent { get; set; }
                public decimal dollarAmount { get; set; }
                public decimal gdbAmount { get; set; }
        }

    try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load("Write down full path");
                    XmlNodeList dataNodes = xmlDoc.SelectNodes("/return-data");

                    foreach (XmlNode node in dataNodes)
                    {
                        Item objItem = new Item();

                   objItem.itemCode=node.SelectSingleNode("item-code").InnerText;
objItem.positionComponent=node.SelectSingleNode("position-component").InnerText;
objbook.dollarAmount=Convert.ToDecimal(node.SelectSingleNode("us-dollar/amount").InnerText);

objbook.gdbAmount=Convert.ToDecimal(node.SelectSingleNode("gdb/amount").InnerText);

                    }

                }
catch(Exception ex)
{
throw ex;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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