如何使用 IXmlSerializable 更改根元素的名称?
How to change name of the root element with IXmlSerializable?
我有下面的代码片段,它使用 IXmlSerializable
:
将 classPerson
的简单实例序列化为 <Person attribute="value" />
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
,我该怎么做?
您可以使用XmlRootAttribute
为根元素指定元素名称:
[XmlRoot(ElementName = "person")]
public class Person : IXmlSerializable
{
...
}
我有下面的代码片段,它使用 IXmlSerializable
:
Person
的简单实例序列化为 <Person attribute="value" />
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
,我该怎么做?
您可以使用XmlRootAttribute
为根元素指定元素名称:
[XmlRoot(ElementName = "person")]
public class Person : IXmlSerializable
{
...
}