使用XmlSerializer进行自定义序列化

我有一个类,我需要从中做一些自定义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 ... } 

这是我的Xml输出:

    2643-15-17 2642-15-17 ...  ... My custom Xml that is correct ..  

我最终想要的是:

    2643-15-17 2642-15-17 ...  ... My custom Xml that is correct ..  

在许多情况下,您可以使用接受XmlAttributeOverridesXmlSerializer构造函数重载来指定此额外名称信息(例如,传递新的XmlRootAttribute ) – 但是,这不适用于arraysAFAIK。 我希望对于string[]例子,手动编写它会更简单。 在大多数情况下, IXmlSerializable是一项额外的工作 – 我尽可能避免这样做的原因。 抱歉。

您可以使用属性标记字段以控制序列化的XML 。 例如,添加以下属性:

 [XmlArray("BatchId")] [XmlArrayItem("id")] public string[] BatchId { get; set; } 

可能会让你到那里。

如果有人仍然在寻找这个你绝对可以使用XmlArrayItem但是这需要是一个类中的属性。

为了便于阅读,您应该使用相同单词的复数和单数。

  ///  /// Gets or sets the groups to which the computer is a member. ///  [XmlArrayItem("Group")] public SerializableStringCollection Groups { get { return _Groups; } set { _Groups = value; } } private SerializableStringCollection _Groups = new SerializableStringCollection();  Test Test2  

大卫