且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

XmlSerializer的列表项元素名称

更新时间:2023-11-25 09:03:40

我不认为有是你控制生成的数组元素的名称的方法。

I don't think there is a way for you to control the name of the generated array elements.

如果你能然而包住另一个类的内部人士集合然后你会拥有比使用生成的输出完全控制 XmlArrayAttribute XmlArrayItemAttribute

If you can however wrap the Persons collection inside another class you will then have complete control over the generated output using XmlArrayAttribute and XmlArrayItemAttribute.

如果您不能创建新类,你可以诉诸实施的IXmlSerializable ,但是这要复杂得多。

If you cannot create this new class you can resort to implementing IXmlSerializable, but this is much more complex.

对于第一种选择示例如下:

An example for the first alternative follows:

[XmlRoot("Context")]
public class Context
{
    public Context() { this.Persons = new Persons(); }

    [XmlArray("Persons")]
    [XmlArrayItem("Person")]
    public Persons Persons { get; set; }
}

public class Persons : List<Human> { }

public class Human
{
    public Human() { }
    public Human(string name) { Name = name; }
    public string Name { get; set; }
}

class Program
{
    public static void Main(string[] args)
    {
        Context ctx = new Context();
        ctx.Persons.Add(new Human("john"));
        ctx.Persons.Add(new Human("jane"));

        var writer = new StringWriter();
        new XmlSerializer(typeof(Context)).Serialize(writer, ctx);

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