我刚开始用 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.