IXmlSerializable 和 XmlRootAttribute [英] IXmlSerializable and XmlRootAttribute

查看:27
本文介绍了IXmlSerializable 和 XmlRootAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 xml 序列化有一个奇怪的要求.

I have a weird requirement on xml serialization.

请参考以下 C# 代码(由于变量rootName"超出范围而无法编译).我的目的是让我的类 GeneralData 成为通用".这意味着可以根据类构造函数的输入参数将此类序列化为具有不同根元素的不同 XML 字符串.

Refer the following C# code (which cannot be compiled due to the variable 'rootName' is out of scope). My intention is to make my class GeneralData be 'general'. Which means this class can be serialized to different XML strings with different root element according to the input parameter for the class constructor.

[XmlRoot(ElementName = rootName)]
public class GeneralData : Dictionary<String, Object>, IXmlSerializable
{
    public string rootName;
    public GeneralData(string rootName)
    {
        this.rootName = rootName;
    }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        foreach (var key in Keys)
        {
            var value = base[key];
            writer.WriteElementString(key, value.ToString());
        }
    }
}

谁能帮我完成任务?也许以完全不同的方式?提前致谢!!

Anyone can help me to accomplish the task? Maybe in a totally different way? Thanks in advance!!

推荐答案

IXmlSerializable 无法控制根元素.所以不,你真的不能那样做.您可以做的最接近的是使用 new XmlSerializer(...) 和重载,让您在运行时指定根名称(进入构造函数),但您应该小心:非-XmlSerializer 的普通构造函数不使用内置的序列化器缓存,这意味着:您最终可以为每个 new XmlSerializer(...) 创建一个新程序集,并且程序集永远不会卸载.如果您不为序列化程序实例添加自己的缓存层,这可能会导致内存泄漏问题.

IXmlSerializable does not get to control the root element. So no, you can't really do that. The closest you could do would be to use new XmlSerializer(...) with the overload that lets you specify the root name at runtime (into the constructor), but you should be cautious: the non-trivial constructors of XmlSerializer do not use the inbuilt serializer-cache, meaning: you can end up creating a new assembly per new XmlSerializer(...), and assemblies are never unloaded. This can lead to memory leak issues if you don't add your own caching layer for the serializer instances.

这篇关于IXmlSerializable 和 XmlRootAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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