Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization: Change the name of the root node without changing the class name

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
}
like image 707
Brandon Boone Avatar asked Feb 26 '23 08:02

Brandon Boone


1 Answers

check the XmlRootAttribute class.

like image 186
Frederik Gheysels Avatar answered Mar 11 '23 05:03

Frederik Gheysels