如何在使用XmlSerializer保留内容的同时更改根元素名称? [英] How do I change root element name while keeping contents using XmlSerializer?

查看:52
本文介绍了如何在使用XmlSerializer保留内容的同时更改根元素名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文档:

<data>
    <elmt1>Element 1</elmt1>
    <elmnt2>Element 2</elmnt2>
    <elmnt3>Element 3</elmnt3>
</data>

我需要反序列化为序列化为不同根名称的对象,而其他所有东西都保持不变.

I need to deserialize to an object that serializes to a different root name with everything else remaining the same.

例如:

<dataNew>
    <elmt1>Element 1</elmt1>
    <elmnt2>Element 2</elmnt2>
    <elmnt3>Element 3</elmnt3>
</dataNew>

序列化时,我们总是可以应用 XmlRootAttribute 序列化为另一个根名称,但是我不确定如何反序列化为另一个 XmlRootAttribute .它会不断导致文档(1,2)出现错误错误,指向根属性.

When serializing, we can always apply XmlRootAttribute to serialize to a different root name but I am not sure how to deserialize to a different XmlRootAttribute. It keeps failing error in document (1,2) pointing to the root attribute.

我该如何实现?

推荐答案

如果只是要更改的根名称,则可以在声明XmlSerializer时指定root属性.

If it's only the root name you want to change you can specify the root attribute when declaring the XmlSerializer.

XmlSerializer xmlSerializer = new XmlSerializer(typeof(data), new XmlRootAttribute("dataNew"));

这篇关于如何在使用XmlSerializer保留内容的同时更改根元素名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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