我可以通过代码,而不是属性指定XMLRoot? [英] Can I specify XMLRoot via code instead of attributes?

查看:203
本文介绍了我可以通过代码,而不是属性指定XMLRoot?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来设置运行时一个对象或类的xmlroot?

Is there a way to set the xmlroot of an object or class during runtime?

[XmlRoot("data")]
public class MyRoot {
    [XmlElement("bar")]
    public List<RemoteHost> Hosts {get;set;}
}



我没有修改的选项类MyRoot在这种情况下;所以,我想指定我想我之前序列化对象使用XmlSerializer的XML被称为数据根名称。

I don't have the option of modifying the class MyRoot in this case; so, I would like to specify that I want the root name to be called "data" before I serialize the object to XML using XmlSerializer.

推荐答案

是的!简单地说:

var serializer = new XmlSerializer(typeof(MyRoot),
    new XmlRootAttribute("data"));



或者更完全,请参阅 XmlAttributeOverrides 。然而,无论是这些您必须缓存和重用序列化的实例,否则你会泄漏组件。

Or more completely, see XmlAttributeOverrides. However, with either of these you must cache and reuse the serializer instance, otherwise you'll leak assemblies.

这篇关于我可以通过代码,而不是属性指定XMLRoot?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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