[英]serialization c# - objects collection
我剛開始用C#編程,但是序列化有問題
我想做的事:
<Products>
<ID>1</ID>
<Product>
<name>Samochod</name>
<price>20</price>
<mass>1000</mass>
</Products>
<Products>
我的點子:
[XmlRoot("Product")]
public class Product
{
[XmlElement("name")]
public string name { get; set; }
[XmlElement("price")]
public decimal price { get; set; }
[XmlElement("mass")]
public double mass { get; set; }
public static void serialization()
{
id iD = new id();
List <id> idlist = new List<id>();
List<Product> listprod = new List<Product>();
idlist.Add(new id() {ID = 1});
listprod.Add(new Product() { name = "Samochod", price = 20, mass = 1000 });
XmlRootAttribute root = new XmlRootAttribute("Products");
TextWriter textwriter = new StreamWriter(@"C:\Products.xml");
XmlSerializer xmlserializer = new XmlSerializer(typeof(List<Product>),root);
xmlserializer.Serialize(textwriter, listprod);
textwriter.Close();
}
}
[XmlRoot("ID")]
public class id:Product
{
[XmlElement("ID")]
public int ID { get; set; }
}
不幸的是,編譯期間出錯。 那么,您能給我一些解決方法嗎?
抱歉,沒有錯誤。 現在看起來像:
<Products>
<Product>
<ID>0</ID>
<name>Samochod</name>
<price>20</price>
<mass>1000</mass>
</Products>
<Products>
但是,當我更改此行時:
idlist.Add(new id() {ID = 1});
對此:
listprod.Add(new id() {ID = 1});
然后我有一個錯誤:
There was an error generating the XML document.
您的idlist
最終未被使用。 由於ID確實是Product
一個屬性,我建議這樣做以簡化如下代碼:
[XmlRoot("Product")]
public class Product
{
[XmlElement("ID")]
public int ID { get; set; }
[XmlElement("name")]
public string name { get; set; }
[XmlElement("price")]
public decimal price { get; set; }
[XmlElement("mass")]
public double mass { get; set; }
public static void serialization()
{
List<Product> listprod = new List<Product>();
listprod.Add(new Product() { ID = 1, name = "Samochod", price = 20, mass = 1000 });
XmlRootAttribute root = new XmlRootAttribute("Products");
TextWriter textwriter = new StreamWriter(@"C:\temp\Products.xml");
XmlSerializer xmlserializer = new XmlSerializer(typeof(List<Product>), root);
xmlserializer.Serialize(textwriter, listprod);
textwriter.Close();
}
}
然后你應該得到
<?xml version="1.0" encoding="utf-8"?>
<Products xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Product>
<ID>1</ID>
<name>Samochod</name>
<price>20</price>
<mass>1000</mass>
</Product>
</Products>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.