我有一个类需要从中执行一些自定义 XML 输出,因此我实现了 IXmlSerializable 接口(interface)。但是,除了我想更改 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
...
}
这是我的 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>
最佳答案
在许多情况下,您可以使用接受 XmlAttributeOverrides
的 XmlSerializer
构造函数重载来指定此额外的名称信息(例如,传递一个新的 XmlRootAttribute
) - 但是,这不适用于数组 AFAIK。我希望对于 string[]
示例,手动编写它会更简单。在大多数情况下,IXmlSerializable
需要做很多额外的工作——出于这样的原因,我尽可能避免使用它。对不起。
关于c# - 使用 XmlSerializer 自定义序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1982104/