我想序列化XmlElement中的XmlAttribute列表。
这是一个程序,您可以在其中添加product's
一些属性,例如name
,description
和一些属性(高度,宽度,品牌,条件) ),但用户可以选择他想要添加的数量(不是固定数量)。
ManagerRoot class
:[Serializable]
public class ManagerRoot
{
[XmlElement("ProductRoot")]
public ProductRoot ProductRoot = new ProductRoot();
}
ProductRoot Class
:[Serializable]
public class ProductRoot
{
[XmlElement("Product")]
public List<Product> ProductList { get; set; }
private void addProduct()
{
//?
}
}
Product class
:[Serializable]
public class Product
{
[XmlIgnore]
private string _header;
[XmlAttribute("Header")]
public string Header
{
get { return this._header; }
set { this._header = value; }
}
[XmlIgnore]
private string _description;
[XmlAttribute("Description")]
public string Description
{
get { return this._description; }
set { this._description = value; }
}
[XmlIgnore]
private string _link;
[XmlAttribute("Link")]
public string Link
{
get { return this._link; }
set { this._link = value; }
}
[XmlIgnore]
private List<string> _properties;
[XmlAttribute("Properties")]
public List<string> Properties
{
get
{
}
set
{
}
}
}
现在我不知道我要对班级内列表的getter
和setter
做些什么。如何添加product
name
,description
,link
&amp;一个filled properties list
?
答案 0 :(得分:0)
对于集合,您需要使用XmlArray和XmlArrayItem对属性进行批注,以定义包含的项目。对于所有基于集合的属性,请遵循相同的ProductList模式。
命名空间ConsoleApplication1 {
[Serializable]
public class ProductRoot
{
[XmlArray]
[XmlArrayItem(ElementName = "Product", Type = typeof(Product))]
public List<Product> ProductList { get; set; }
}
[Serializable]
public class Product
{
[XmlIgnore]
private string _header;
[XmlAttribute("Header")]
public string Header {
get { return this._header; }
set { this._header = value; }
}
[XmlIgnore]
private string _description;
[XmlAttribute("Description")]
public string Description {
get { return this._description; }
set { this._description = value; }
}
[XmlIgnore]
private string _link;
[XmlAttribute("Link")]
public string Link {
get { return this._link; }
set { this._link = value; }
}
[XmlIgnore]
private List<string> _properties;
[XmlAttribute("Properties")]
public List<string> Properties { get; set; }
}
static class Program
{
static void Main() {
var productRoot = new ProductRoot();
var products = new List<Product>();
products.Add(new Product() { Description = "A", Properties = new List<string> { "PropA" } });
products.Add(new Product() { Description = "B", Properties = new List<string> { "PropB" } });
productRoot.ProductList = products;
Test(productRoot);
}
static void Test<T>(T obj) {
using (MemoryStream stream = new MemoryStream()) {
XmlSerializer s = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter()) {
using (var writer = XmlWriter.Create(stringWriter)) {
s.Serialize(stringWriter, obj);
}
Console.WriteLine(stringWriter.ToString());
}
}
}
}