简体   繁体   中英

Property isn't serialized

        [XmlIgnore()]
        public List<MyObject> ListMyObjects = new List<MyObject>();
        public List<string> MyProperty
        {
            get
            {
                List<string> list = new List<string>();
                foreach (MyObject obj in ListMyObjects)
                    list.Add(obj.Name);
                return list;
            }
            set
            {
                foreach (string name in value)
                    ListMyObjects.Add(new MyObject(name));
            }
        }

Why is MyPropery not serializing? I am using Xml Serializer.

Somebody please format my code, it isn't formating on iPad.

Please try this,

public string[] MyProperty
        {
            get
            {
                List<string> list = new List<string>();
                foreach (MyObject obj in ListMyObjects)
                    list.Add(obj.Name);
                return list.ToArray();
            }
            set
            {
                foreach (string name in value)
                    ListMyObjects.Add(new MyObject(name));
            }
        }

Working fine for me.. Check this..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Serialization_Xml
{
    class Program
    {
        static void Main(string[] args)
        {
            Data data = new Data();
            List<string> mylist = new List<string>();
            mylist.Add("A");
            mylist.Add("B");
            data.MyProperty = mylist;
            FileStream fs = new FileStream("Data.xml", FileMode.Create);
            XmlSerializer serializer= new XmlSerializer(typeof(Data));
            serializer.Serialize(fs, data);
        }
    }

   public class Data
    {
        [XmlIgnore()]
        public List<MyObject> ListMyObjects = new List<MyObject>();
        public List<string> MyProperty
        {
            get
            {
                List<string> list = new List<string>();
                foreach (MyObject obj in ListMyObjects)
                    list.Add(obj.Name);
                return list;
            }
            set
            {
                foreach (string name in value)
                    ListMyObjects.Add(new MyObject(name));
            }
        }

    }

    public class MyObject
    {
        public string Name;
        public MyObject(string name)
        {
            Name = name;
        }
    }
}

Output:

<?xml version="1.0"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MyProperty>
    <string>A</string>
    <string>B</string>
  </MyProperty>
</Data>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM