我有一个类,我需要做一些自定义的XML输出,因此我实现了IXmlSerializable接口。但是,我想用默认序列化输出一些字段,但我想更改xml标记名称。当我调用serializer.Serialize时,我得到了XML中的默认标签名称。我可以改变这些吗?自定义序列化使用XmlSerializer
这里是我的代码:
public class myClass: IXmlSerializable
{
//Some fields here that I do the custom serializing on
...
// These fields I want the default serialization on except for tag names
public string[] BatchId { get; set; }
...
... ReadXml and GetSchema methods are here ...
public void WriteXml(XmlWriter writer)
{
XmlSerializer serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(writer, BatchId);
... same for the other fields ...
// This method does my custom xml stuff
writeCustomXml(writer);
}
// My custom xml method is here and works fine
...
}
这里是我的XML输出:
<MyClass>
<ArrayOfString>
<string>2643-15-17</string>
<string>2642-15-17</string>
...
</ArrayOfString>
... My custom Xml that is correct ..
</MyClass>
我想直到结束是:
<MyClass>
<BatchId>
<id>2643-15-17</id>
<id>2642-15-17</id>
...
</BatchId>
... My custom Xml that is correct ..
</MyClass>
多久你序列化/反序列化?在应用生命周期内或仅在启动/关闭期间执行100次。如果前者我有一个更灵活的实现。 – 2009-12-30 20:30:59
真的只有序列化一次。这个应用程序是一个简单的工具,它从专有数据库格式中提取数据并保存到xml。所以我将数据拉入对象模型,然后立即序列化。大部分数据很简单,所以我不需要实现IXmlSerializable ...但是这个特定的数据有点痛苦。 – KrisTrip 2009-12-30 20:34:50
看看这里,代码是MIT http://code.google.com/p/videobrowser/source/browse/MediaBrowser/Library/Persistance/XmlSettings.cs还有一个单元测试,你可能不得不扩展一下,但所有的架构都在那里。加上你的场景,它会比XmlSerializer更好地执行 – 2009-12-30 20:41:23