序列化:改变根节点名称,不改变类名
目标
获取一个名为“Item”的类,并将其序列化 XML 输出为:
<Template><!--some properties --></Template>
问题
根节点派生自实现 IXmlSerialized 的类名。
// By the time I get here 'writer' already has a root node
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("Template");
// write out the properties
writer.WriteEndElement();
}
所以我最终得到的 XML 看起来像
<Item><Template><!-- some properties --></Template></Item>
问题
是否有一个属性,一个我可以覆盖的属性,或者任何东西来获得我想要的效果(除了更改类名)?
谢谢!
感谢 Frederik 的解决方案!
由于这个问题在我对 @Frederik Gheysels 答案的评论中得到了回答,我想我会把它放在这里,这样它就不会被埋没。
只需向您的类添加一个 XmlRoot 属性,这将更改根节点的输出 xml。
例子:
[XmlRoot("Template")]
public class Item : IXmlSerializable
{
//Item's properties
}
Goal
Take a class named "Item" and output its serialized XML as:
<Template><!--some properties --></Template>
Problem
The root node is derived off the class name that is implementing IXmlSerializable.
// By the time I get here 'writer' already has a root node
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("Template");
// write out the properties
writer.WriteEndElement();
}
So I wind up with XML that looks like
<Item><Template><!-- some properties --></Template></Item>
Question
Is there an attribute, a property I can override, or anything to get my desired effect (aside from changing the class name)?
Thanks!
Resolution thanks to Frederik!
Since the question is sort of answered in my comment of @Frederik Gheysels answer, I thought I would put it here so it doesn't get buried.
Just add an XmlRoot attribute to your class and this will change the output xml of the root node.
Example:
[XmlRoot("Template")]
public class Item : IXmlSerializable
{
//Item's properties
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查 XmlRootAttribute 类。
check the XmlRootAttribute class.