Here is a test class:
[XmlRoot("Test")]
class Test : IXmlSerializable
{
public string Attr { get; set; }
// ... more properties here...
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("attr", Attr);
writer.WriteStartElement("InnerTest"); // <-- exception
// ... write inner stuff
writer.WriteEndElement();
}
}
When I call WriteXml, an exception is thrown:
Index was outside the bounds of the array.
at System.Xml.XmlTextWriter.WriteEndStartTag(Boolean empty)
at System.Xml.XmlTextWriter.AutoComplete(Token token)
at System.Xml.XmlTextWriter.WriteStartElement(String prefix, String localName, String ns)
at System.Xml.XmlWriter.WriteStartElement(String localName)
at Tests.Test.WriteXml(XmlWriter writer)
In examples on the internet this code doesn't cause any issues (e.g. http://www.codeproject.com/Articles/43237/How-to-Implement-IXmlSerializable-Correctly), yet for me it doesn't work. What can be the reason?
Update: Eventually, I would like the class to be serialized like this:
<Test attr="..."><InnerTest>...</InnerTest></Test>
I think your issue may be more about how you're calling the serializer than how the WriteXml code is implemented. For example in LINQPad I did this:
Test t = new Test() { Attr = "cat" };
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test));
StringWriter w = new StringWriter();
xmlSerializer.Serialize(w, t);
w.ToString().Dump();
And I received this output:
<?xml version="1.0" encoding="utf-16"?>
<Test attr="cat">
<InnerTest />
</Test>