序列化:更改根节点的名称而不更改类名

时间:2023-01-19 09:27:04

Goal

Take a class named "Item" and output its serialized XML as:

获取名为“Item”的类并将其序列化XML输出为:

<Template><!--some properties --></Template>

Problem

The root node is derived off the class name that is implementing IXmlSerializable.

根节点是从实现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

所以我最终看起来像XML

<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.

由于这个问题在我对@Frederik Gheysels回答的评论中有所回答,我想我会把它放在这里,所以它不会被埋没。

Just add an XmlRoot attribute to your class and this will change the output xml of the root node.

只需向您的类添加XmlRoot属性,这将更改根节点的输出xml。

Example:

[XmlRoot("Template")]
public class Item : IXmlSerializable
{
   //Item's properties
}

1 个解决方案

#1


6  

check the XmlRootAttribute class.

检查XmlRootAttribute类。

#1


6  

check the XmlRootAttribute class.

检查XmlRootAttribute类。