Custom Serialization using XmlSerializer

11,697

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

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

Share:
11,697
KrisTrip
Author by

KrisTrip

I have bachelors and masters degrees in Software Engineering. I work as a software developer using mostly C# (with some VB and FORTRAN thrown in for good measure)

Updated on June 04, 2022

Comments

  • KrisTrip
    KrisTrip almost 2 years

    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>