如何在自定义 XML 序列化方法中使用默认 XML 序列化 [英] How to use default XML serialization from within custom XML serialization methods

查看:38
本文介绍了如何在自定义 XML 序列化方法中使用默认 XML 序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .NET 中有一个实现 IXmlSerializable 的类.我想序列化它的属性,但它们可能是复杂的类型.这些复杂类型将与 XML 序列化兼容,但它们本身不实现 IXmlSerializable.从我的 ReadXml 和 WriteXml 方法中,我如何调用传递给我的 XmlReader/XmlWriter 上的默认读/写逻辑.

I have a class in .NET that implements IXmlSerializable. I want to serialize its properties, but they may be complex types. These complex types would be compatible with XML serialization, but they don't implement IXmlSerializable themselves. From my ReadXml and WriteXml methods, how do I invoke the default read/write logic on the XmlReader/XmlWriter that is passed to me.

也许代码会让我更清楚我想要什么:

Perhaps code will make it clearer what I want:

public class MySpecialClass : IXmlSerializable
{
    public List<MyXmlSerializableType> MyList { get; set; }

    System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
    {
        return null;
    }

    void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
    {
        //  Read MyList from reader, but how?
        //  Something like this?
        //  MyList = (List<MyXmlSerializableType>)
            reader.ReadObject(typeof(List<MyXmlSerializableType>));
    }

    void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
    {
        //  Write MyList to writer, but how?
        //  Something like this?
        //  writer.WriteObject(MyList)

    }
}

推荐答案

对于编写器,您可以为 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).

这篇关于如何在自定义 XML 序列化方法中使用默认 XML 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆