IXmlSerializable.WriteXml 尝试写入内部标记时出现异常

Exception during IXmlSerializable.WriteXml when attempting to write an inner tag

这是一个测试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();
        }
    }

当我调用 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) 

在 Internet 上的示例中,此代码不会导致任何问题(例如 http://www.codeproject.com/Articles/43237/How-to-Implement-IXmlSerializable-Correctly),但对我来说它不起作用。可能是什么原因?

更新: 最后,我希望 class 像这样序列化:

<Test attr="..."><InnerTest>...</InnerTest></Test>

我认为您的问题可能更多地与您如何调用序列化程序有关,而不是与 WriteXml 代码的实现方式有关。例如在 LINQPad 中我这样做了:

Test t = new Test() { Attr = "cat" };       

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test));      
StringWriter w = new StringWriter();
xmlSerializer.Serialize(w, t);  
w.ToString().Dump();

我收到了这个输出:

<?xml version="1.0" encoding="utf-16"?>
<Test attr="cat">
  <InnerTest />
</Test>