序列化对象集合

本文关键字:集合 对象 序列化 | 更新日期: 2023-09-27 18:33:32

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