使用List<>序列化类到XML

时间:2016-12-29 13:41:33

标签: c# xml-serialization

我对XML很陌生。我想序列化一个类,使用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 个答案:

答案 0 :(得分:0)

1.请使用System.Xml作为参考添加; 2.以这种方式创建一个名为Item的类

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