XML序列化对象列表

时间:2015-06-15 18:14:03

标签: c# xml serialization xml-serialization

查看有关XML序列化的Microsoft文章:

https://msdn.microsoft.com/en-us/library/58a18dwa.aspx

他们在“序列化对象数组”下给出了一个示例,如下所示:

public class PurchaseOrder
{
    public Item [] ItemsOrders
}

public class Item
{
    public string ItemID
    public decimal ItemPrice
}

输出:

<PurchaseOrder>
    <Items>
        <Item>
            <ItemID>aaa111</ItemID>
            <ItemPrice>34.22</ItemPrice>
        </Item>
        <Item>
            <ItemID>bbb222</ItemID>
            <ItemPrice>2.89</ItemPrice>
        </Item>
    </Items>
</PurchaseOrder>

困扰我的是“Items”标签。在我看来,只有“Item”标签应该是“PurchaseOrder”的子项。 “Items”标签似乎不必要且令人困惑。我错了。

有没有办法让这个例子像这样序列化:

<PurchaseOrder>
    <Item>
        <ItemID>aaa111</ItemID>
        <ItemPrice>34.22</ItemPrice>
    </Item>
    <Item>
        <ItemID>bbb222</ItemID>
        <ItemPrice>2.89</ItemPrice>
    </Item>
</PurchaseOrder>

2 个答案:

答案 0 :(得分:5)

您可以使用attributes控制序列化。从“Controlling XML Serialization using Attributes”:要删除代表整个数组的元素,请使用[XmlElement]属性:

public class Group{
    [XmlElement]
    public Employee[] Employees;
}

这会产生

<Group>
    <Employees>
        <Name>Haley</Name>
    </Employees>
    <Employees>
        <Name>Noriko</Name>
    </Employees>
    <Employees>
        <Name>Marco</Name>
    </Employees>
</Group>

答案 1 :(得分:1)

您可以使用XmlElement属性指定要用于每个项目的名称:

namespace ConsoleApplication1
{
    using System;
    using System.IO;
    using System.Xml.Serialization;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var order = new PurchaseOrder { ItemsOrders = new Item[2] };

            order.ItemsOrders[0] = new Item { ItemID = "1", ItemPrice = 1723 };
            order.ItemsOrders[1] = new Item { ItemID = "2", ItemPrice = 4711 };

            var serializer = new XmlSerializer(typeof(PurchaseOrder));

            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, order);

                Console.WriteLine(writer.ToString());
            }
        }
    }

    public class PurchaseOrder
    {
        [XmlElement("Item")]
        public Item[] ItemsOrders { get; set; }
    }

    public class Item
    {
        public string ItemID { get; set; }

        public decimal ItemPrice { get; set; }
    }
}
<?xml version="1.0" encoding="utf-16"?>
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Item>
    <ItemID>1</ItemID>
    <ItemPrice>1723</ItemPrice>
  </Item>
  <Item>
    <ItemID>2</ItemID>
    <ItemPrice>4711</ItemPrice>
  </Item>
</PurchaseOrder>
Press any key to continue . . .