XML Serializer - 隐藏元素

时间:2016-04-06 14:11:06

标签: c# xml-serialization

下午好,

我有以下代码:

public class PurchaseOrder
{
    public Item [] Items
}
public class Item
{
    public string ItemID
    public decimal ItemPrice
}

序列化时,会生成以下XML:

<PurchaseOrder xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    **<Items>**
        <Item>
            <ItemID>aaa111</ItemID>
            <ItemPrice>34.22</ItemPrice>
        <Item>
        <Item>
            <ItemID>bbb222</ItemID>
            <ItemPrice>2.89</ItemPrice>
        <Item>
    **</Items>**
</PurchaseOrder>

有没有办法省略<Items> </Items>元素(粗体) - 但继续包含<Item>元素?

1 个答案:

答案 0 :(得分:1)

如果使用列表而不是数组,则如下所示:

public class PurchaseOrder
{
    [XmlElement("Item")]
    public List<Item> Items;
}
public class Item
{
    public string ItemID;
    public decimal ItemPrice;
}

将产生:

<PurchaseOrder xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Item>
        <ItemID>aaa111</ItemID>
        <ItemPrice>34.22</ItemPrice>
    <Item>
    <Item>
        <ItemID>bbb222</ItemID>
        <ItemPrice>2.89</ItemPrice>
    <Item>
</PurchaseOrder>