1

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.

2 Answers2

1

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);
EkoostikMartin
  • 6,831
  • 2
  • 33
  • 62
  • I don't think that would work as he's not serializing `MyClass` using the default XmlSerializer implementation. It's coming out from appending a default XmlSerialization of type `Collection`. – Chris Sinclair Jun 21 '12 at 14:34
  • I am out of office now, I will try it tommorow and let you know. By looking at edited code, I think it would definatly work :) –  Jun 21 '12 at 15:50
0

Another way that doesn't create a new XmlSerializer:

public void WriteXml(XmlWriter writer)
{
    writer.WriteAttributeString("Version", vesrion.ToString(CultureInfo.InvariantCulture));
    writer.WriteStartElement("MyCollection");
    foreach (int collint in Testcoll)
    {
        writer.WriteElementString("int", collint.ToString(CultureInfo.InvariantCulture));
    }
    writer.WriteEndElement();
}
Cœur
  • 37,241
  • 25
  • 195
  • 267