开发者

Custom Serialization using XmlSerializer

I have a class that I need to do some custom XML output from, thus I implement the IXmlSerializable interface. However, some of the fields I want to output with the default serialization except I want to change the xml tag names. When I call serializer.Serialize, I get default tag names in the XML. Can I change these somehow?

Here is my code:

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
    ...
}

Here is my Xml output:

  <MyClass>
    <ArrayOfString>
  开发者_Python百科    <string>2643-15-17</string>
      <string>2642-15-17</string>
      ...
    </ArrayOfString>
    ... My custom Xml that is correct ..
  </MyClass>

What I want to end up with is:

  <MyClass>
    <BatchId>
      <id>2643-15-17</id>
      <id>2642-15-17</id>
      ...
    </BatchId>
    ... My custom Xml that is correct ..
  </MyClass>


In many cases, you can use the XmlSerializer constructor-overload that accepts a XmlAttributeOverrides to specify this extra name information (for example, passing a new XmlRootAttribute) - however, this doesn't work for arrays AFAIK. I expect for the string[] example it would be simpler to just write it manually. In most cases, IXmlSerializable is a lot of extra work - I avoid it as far as possible for reasons like this. Sorry.


You can tag your fields with attributes to control the serialized XML. For example, adding the following attributes:

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

will probably get you there.


If anyone is still looking for this you can definitely use the XmlArrayItem however this needs to be a property in a class.

For readability you should use the plural and singular of the same word.

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

David

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜