...">

Rename a serializable class

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 write to get the following tag designation (products and lower case)?

 <products> <product/> </products> 
+4
source share
2 answers

Plain; do not 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 { } 
+2
source

How do you do serialization? I used the 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> 
+1
source

Source: https://habr.com/ru/post/1303674/


All Articles