views:

451

answers:

2

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>
+2  A: 

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.

womp
Tried that. No luck.
KrisTrip
+2  A: 

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.

Marc Gravell
XmlSerializer is an old piece of unmaintained, inefficient technology that should have been deprecated by MS ages ago, or at the bare minimum reimplemented. I have only had trouble with it. Better off use protocol buffers :p
Sam Saffron
How tempting is it to see if I can crank the output of pb-net to xml ;-p
Marc Gravell
you should totally do that, and make it pluggable so people can implement their own persistence format, then you could even use sqlite as a data store ...
Sam Saffron