Search code examples
c#ixmlserializable

IXmlSerializable change xml tag names


I have class with collection as below

public class MyClass:IXmlSerializable
{
    int vesrion;
    private Collection<int> testcoll;
}

to serialize it I have written WriteXML as below

public void WriteXml(XmlWriter writer)
{

    writer.WriteAttributeString("Version", this.vesrion.ToString());    

    XmlSerializer serializer = new XmlSerializer(typeof(Collection<int>));
    serializer.Serialize(writer, Testcoll);
 }

Now output xml have tag "ArrayOfInt" as for Testcoll. But I want to change this name to something different "MyCollection".

Please tell me how to achieve this.


Solution

  • Use an attribute over the field, like this:

    [XmlElement(ElementName = "MyCollection")]
    private Collection<int> testcoll;
    

    EDIT: @comments, missed those details, see below for answer that works (compiled and tested)

    XmlSerializer serializer = new XmlSerializer(typeof(Collection<int>), new XmlRootAttribute("MyCollection"));
    serializer.Serialize(writer, Testcoll);