Dipiks
Dipiks

Reputation: 3928

How to rename the serialization root object name in a class?

(First, feel free to edit my title, I really don't find a better one for my problem)

I got my root class:

[XmlRoot("ProductList")]
public class Product
{
    [XmlElement("Property1")]
    public string property1 { get; set; }
    [XmlElement("Property2")]
    public Property2 property2 { get; set; }
    [XmlArray("Property3Array")]
    [XmlArrayItem("Property3ArrayItem")]

    public List<Property3> property3{ get; set; }
}

I'm serializing the List of Products like this:

public void Execute(IJobExecutionContext context)
{
    var products = _productionService.GetAllProducts();

    XmlSerializer xs = new XmlSerializer(typeof(List<Product>));

    using (StreamWriter sw = new StreamWriter("products.xml"))
    {
        xs.Serialize(sw, products);
    }

}

The serialization is working properly BUT, in my products.xml file, the root node is:

<ArrayOfProduct xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    ...
</ArrayOfProduct>

But I want the root element of the list to be named ProductList

I tried with [XmlRoot("ProductList")] But that doesn't work.

So, how can I rename the name of the root xml object of a List<Class> ?

Upvotes: 1

Views: 1364

Answers (1)

Charles Mager
Charles Mager

Reputation: 26233

Use a constructor overload that accepts an XmlRootAttribute.

var xs = new XmlSerializer(typeof(List<Product>), new XmlRootAttribute("ProductList"));

See this fiddle for a working demo.

Upvotes: 2

Related Questions