XML 对象的序列化列表

XML Serialization List of Objects

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

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

他们在 "Serializing an Array of Objects" 下举了一个例子如下:

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>

您可以使用 attributes.From 控制序列化 “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>

您可以使用 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 . . .