序列化c# - 对象集合

时间:2013-09-30 20:28:47

标签: c# serialization

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

1 个答案:

答案 0 :(得分:0)

您的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>