这是一个测试类:
[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();
}
}
当我调用 WriteXml 时,会引发异常:
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)
在互联网上的示例中,此代码不会导致任何问题(例如http://www.codeproject.com/Articles/43237/How-to-Implement-IXmlSerializable-Correctly),但对我来说它不起作用。可能是什么原因?
更新: 最终,我希望类像这样被序列化:
<Test attr="..."><InnerTest>...</InnerTest></Test>