2

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

  <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>
4

3 回答 3

7

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

于 2009-12-30T20:20:37.950 回答
3

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

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

可能会让你到达那里。

于 2009-12-30T20:06:26.890 回答
0

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

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

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



<Groups>
   <Group>Test</Group>
   <Group>Test2</Group>
</Groups>

大卫

于 2016-09-01T14:00:20.117 回答