Serializing Lists of Classes to XML

前端 未结 4 1965
清歌不尽
清歌不尽 2020-12-01 03:44

I have a collection of classes that I want to serialize out to an XML file. It looks something like this:

public class Foo
{
  public List BarList         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-01 04:06

    Just to check, have you marked Bar as [Serializable]?

    Also, you need a parameter-less ctor on Bar, to deserialize

    Hmm, I used:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
    
            Foo f = new Foo();
    
            f.BarList = new List();
    
            f.BarList.Add(new Bar { Property1 = "abc", Property2 = "def" });
    
            XmlSerializer ser = new XmlSerializer(typeof(Foo));
    
            using (FileStream fs = new FileStream(@"c:\sertest.xml", FileMode.Create))
            {
                ser.Serialize(fs, f);
            }
        }
    }
    
    public class Foo
    {
        [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")]
        public List BarList { get; set; }
    }
    
    [XmlRoot("Foo")]
    public class Bar
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    }
    

    And that produced:

    
    
      
        
          abc
          def
        
      
    
    

提交回复
热议问题