c# - 使用 XmlSerializer 自定义序列化

标签 c# .net-3.5 xml-serialization ixmlserializable

我有一个类需要从中执行一些自定义 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>

最佳答案

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

关于c# - 使用 XmlSerializer 自定义序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1982104/

相关文章:

c# - 子集和问题

c# - 使用 XmlSerializer 序列化 char 数据类型

C# XML 序列化 - 如何序列化继承 List<Object> 的类中的属性?

C# 无法使用 List<CustomObject> 作为属性序列化类

c# - 如何使用 C# 检查邮件已读或未读属性 (Lotus Notes)

.net-3.5 - 本地化 IEnumerable 的最佳方法是什么?

c# - ExpressionTree 重写 - 参数 'x' 不在范围内

c# - 序列化 bool ?错误反射(reflect)类型

c# - 从 C# 调用 C dll 代码?

c# - 字典初始化器具有不同的行为,并在与数组初始化器组合使用时引发运行时异常