且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在自定义 XML 序列化方法中使用默认 XML 序列化

更新时间:2022-06-22 08:55:37

对于编写器,您可以为 MySerializableType 创建一个 XmlSerializer,然后通过它将列表序列化到您的编写器.

For the writer, you could just create an XmlSerializer for the MySerializableType, then serialize the list through it to your writer.

void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
    // write xml decl and root elts here
    var s = new XmlSerializer(typeof(MySerializableType)); 
    s.Serialize(writer, MyList);
    // continue writing other elts to writer here
}

读者也有类似的方法.编辑:要仅读取列表,并在列表完成后停止读取,但在流结束之前,您需要使用 ReadSubTree(来源 Marc Gravell).

There is a similar approach for the reader. EDIT: To read only the list, and to stop reading after the List is complete, but before the end of the stream, you need to use ReadSubTree (credit Marc Gravell).