对象的XML序列化列表 [英] XML Serialization List of Objects

查看:70
本文介绍了对象的XML序列化列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Looking at the Microsoft article on XML Serialization:

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

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

They give an example under "Serializing an Array of Objects" as below:

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>

困扰我的是商品"标签.在我看来,仅"Item"标签应该是"PurchaseOrder"的子级.项目"标签似乎不必要且令人困惑.我可能是错的.

What bothers me is the "Items" tag. Seems to me like only the "Item" tag should be a child of "PurchaseOrder". The "Items" tag seems unnecessary and confusing. I could be wrong.

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

Is there a way to get this example to serialize like this:

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

推荐答案

您可以使用属性控制序列化.来自" [XmlElement] 属性:

You can control the serialization using attributes.From "Controlling XML Serialization using Attributes": To remove the element which stands for the entire array, use the [XmlElement] attribute:

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

这产生

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

这篇关于对象的XML序列化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆