C# - 序列化时在节点中添加属性

时间:2016-05-10 07:41:28

标签: c# xml serialization attributes

我有两节课:

public class Customer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

public class myclass
{
    public string Propertie1 { get; set; }

    public Customer[] Customers { get; set; }
}   

在实例+序列化器上:

myclass c = new myclass()
{
    Propertie1 = "value",

    Customers = new Customer[]
    {
        new Customer()
        {
            FirstName = "FirstName1",
            LastName = "LastName1"
        },
        new Customer()
        {
            FirstName = "FirstName2",
            LastName = "LastName2"
        }
    }
};

XmlSerializer xs = new XmlSerializer(typeof(myclass));
using (StreamWriter wr = new StreamWriter(@"c:/Temp/customers.xml"))
{
    xs.Serialize(wr, c);
}

如何在每个节点中添加属性?例如

使用XmlAttribute可能吗?但我不知道如何使用

感谢' S

1 个答案:

答案 0 :(得分:0)

我会做以下事情:

添加另一个属性

public class Customer
{
    [XmlAttribute]
    public int id {get;set;}

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

在为Customer对象分配值时:

new Customer()
        { 
            id = 1,
            FirstName = "FirstName1",
            LastName = "LastName1"
        },

当id分配如下时,这将为每个客户提供输出

<myclass>
    <Customer id=1>
      <FirstName>FirstName1</FirstName>
      <LastName>LastName1</LastName>
    </Customer>
    <Customer id=2>
      <FirstName>FirstName2</FirstName>
      <LastName>LastName2</LastName>
    </Customer>
</myclass>

我认为myClass中的Propertie1也会有[XmlAttribute] 制作它

<myclass Propertie1 = "<assinged value>">

post 提供了一个很好的概述