Custom Serialization using XmlSerializer

梦想与她 提交于 2019-12-22 18:16:11

问题


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

回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/1982104/custom-serialization-using-xmlserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!