4

如果我使用 XmlSerializer 序列化以下代码。

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

我得到以下xml

<ArrayOfProduct>
  <Product/>
</ArrayOfProduct>

我如何编写以获得标签的以下命名(产品和小写产品)?

<products>
  <product/>
</products>
4

2 回答 2

2

简单的; 不要继承自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
{
}
于 2010-03-10T13:33:40.813 回答
1

你是如何进行序列化的?我使用了以下代码:

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();
}

并得到了这个结果:

<?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>
于 2010-03-10T13:36:29.940 回答