如何使用IXmlSerializable更改根元素的名称?

时间:2018-08-09 21:09:11

标签: c# .net xml serialization xml-serialization

下面有一段代码,其中使用Person将一个类的简单实例<Person attribute="value" />序列化为IXmlSerializable

using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

public class Person : IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return null;
    }
    public void ReadXml(XmlReader xmlReader)
    {
        throw new System.NotImplementedException();
    }
    public void WriteXml(XmlWriter xmlWriter)
    {
        xmlWriter.WriteAttributeString("attribute", "value");
    }
}

class Program
{    
    public static void Main()
    {
        var xmlWriterSettings = new XmlWriterSettings
        {
            Indent = true,
            OmitXmlDeclaration = true
        };

        using (var xmlTextWriter = XmlWriter.Create(Console.Out, xmlWriterSettings))
        {
            var xmlSerializer = new XmlSerializer(typeof(Person));
            var person = new Person();
            xmlSerializer.Serialize(xmlTextWriter, person);
        }
    }
}

我正在寻找一种将Person的元素名称修改为person的方法,该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用XmlRootAttribute为根元素指定元素名称:

[XmlRoot(ElementName = "person")]
public class Person : IXmlSerializable
{
    ...
}