下面有一段代码,其中使用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
的方法,该怎么做?
答案 0 :(得分:1)
您可以使用XmlRootAttribute
为根元素指定元素名称:
[XmlRoot(ElementName = "person")]
public class Person : IXmlSerializable
{
...
}