Kri*_*rip 2 c# xml-serialization ixmlserializable .net-3.5
我有一个类,我需要从中做一些自定义XML输出,因此我实现了IXmlSerializable接口.但是,我想要使用默认序列化输出的一些字段,除了我想要更改xml标记名称.当我调用serializer.Serialize时,我在XML中获得了默认的标记名称.我能以某种方式改变这些吗?
这是我的代码:
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
...
}
Run Code Online (Sandbox Code Playgroud)
这是我的Xml输出:
<MyClass>
<ArrayOfString>
<string>2643-15-17</string>
<string>2642-15-17</string>
...
</ArrayOfString>
... My custom Xml that is correct ..
</MyClass>
Run Code Online (Sandbox Code Playgroud)
我最终想要的是:
<MyClass>
<BatchId>
<id>2643-15-17</id>
<id>2642-15-17</id>
...
</BatchId>
... My custom Xml that is correct ..
</MyClass>
Run Code Online (Sandbox Code Playgroud)
在许多情况下,您可以使用XmlSerializer接受a 的构造函数重载XmlAttributeOverrides来指定此额外名称信息(例如,传递新的XmlRootAttribute) - 但是,这不适用于阵列AFAIK.我希望在这个string[]例子中,手动编写它会更简单.在大多数情况下,IXmlSerializable还有很多额外的工作 - 我会尽可能地避免这样做.抱歉.