【发布时间】:2018-08-09 21:09:11
【问题描述】:
我有下面代码的 sn-p,它使用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的方法,我该怎么做?
【问题讨论】:
-
我稍微修改了您的问题,添加了
using指令,将Do放在一个类中并将其重命名为Main- 这样任何人都可以复制/粘贴/编译/跑。希望你没事。 -
@Daisy Shipton 当然,谢谢!
-
如果您真的关心控制根命名空间 prefix(而不仅仅是根命名空间),那么您可能无法通过
XmlSerializer属性控制它,请参阅@ 987654322@ 和 How to add namespace prefix for IXmlSerializable type 没有接受的答案。
标签: c# .net xml serialization xml-serialization