Rename serializable class

953 views Asked by At

If i Serializable the following code using XmlSerializer.

[XmlRoot("products")]
public class Products : List<Product>
{
}
public class Product
{
}

I get the following xml

<ArrayOfProduct>
  <Product/>
</ArrayOfProduct>

How to i write to get the following naming of the tags (products and lower case product)?

<products>
  <product/>
</products>
2

There are 2 answers

1
Marc Gravell On

Simple; don't inherit from List<T>:

[XmlRoot("products")]
public class ProductWrapper
{
    private List<Product> products = new List<Product>();

    [XmlElement("product")]
    public List<Product> Products { get {return products; } }
}
public class Product
{
}
1
Andrew Bezzub On

How are you doing serialization? I've used following code:

Products products = new Products();
products.Add(new Product());

XmlSerializer serializer = new XmlSerializer(typeof(Products));

using (StringWriter sw = new StringWriter())
{
    serializer.Serialize(sw, products);

    string serializedString = sw.ToString();
}

and got this result:

<?xml version="1.0" encoding="utf-16"?>
<products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Product />
</products>