views:

68

answers:

2

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  A: 

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
{
}
Marc Gravell
i agree with proposed solution, but it is interesting why [XmlRoot("products")] is ignored in author's code
Andrey
+1  A: 

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"&gt;
  <Product />
</products>
Andrew Bezzub
Hmm.. add `[XmlType("product")]` to `Product` ftw ;-p
Marc Gravell