Skip to main content
 首页 » 编程设计

c#之类序列化到 XML

2024年02月13日11jiqing9006

给定以下类设计:

 public class AllUserCollections 
    { 
        public List<UserCollection> UserCollections { get; set; } 
 
        public AllUserCollections() 
        { 
            this.UserCollections = new List<UserCollection> (); 
        } 
    } 
 
    public class UserCollection 
    { 
        public string UserGroup { get; set; } 
        public Dictionary<int,User> Users { get; set; } 
 
        public UserCollection(string userGroup) 
        { 
            this.UserGroup = userGroup; 
            this.Users = new Dictionary<int, User> (); 
        } 
    } 
 
    public class User 
    { 
        public int ID { get; set; } 
        public string Name { get; set; } 
        public string Location { get; set; } 
        public AgeGroup UserAgeGroup { get; set; } 
    } 
 
    public enum AgeGroup 
    { 
        Twenties, 
        Thirties, 
        Fourties, 
    } 

如何使用我现有的序列化类将其序列化为 XML?

public static class HardDriveService 
    { 
        private static string docsFolderPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); 
        private const string fileName = "AllUserCollections.xml"; 
        private static string filePath = Path.Combine(docsFolderPath, fileName); 
 
        private static bool FileExists(string fullFilePath) 
        { 
            if (File.Exists (fullFilePath))  
                return true; 
 
            return false; 
        } 
 
        public static void Save(AllUserCollections allUserCollections) 
        { 
            if (FileExists(filePath)) 
            { 
                File.Delete (filePath); 
            } 
 
            XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType()); 
            using(StreamWriter writer = new StreamWriter(filePath)) 
            { 
                serializer.Serialize(writer.BaseStream, allUserCollections); 
            } 
        } 
 
        public static AllUserCollections Read() 
        { 
            AllUserCollections allUserCollections = new AllUserCollections(); 
            XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType()); 
 
            if (FileExists(filePath)) 
            { 
                StreamReader reader = new StreamReader(filePath); 
                object deserialized = serializer.Deserialize(reader.BaseStream); 
                allUserCollections = (AllUserCollections)deserialized; 
            } 
 
            return allUserCollections; 
        } 
 
 
    }//End of class. 

问题

我的代码似乎在这一行失败了 -

XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType()); 

不知道是不是跟需要显式标记为“可序列化”的类有关?我该怎么做?

用法 此代码将在 iPhone 上运行,并直接从应用程序将 XML 保存/读取到 iPhone 硬盘上。

请您参考如下方法:

XMLSerializer 不支持开箱即用的字典。您的 UserCollection 类有一个字典。请参阅此链接以获取解决方法。 Why doesn't XmlSerializer support Dictionary?

除此之外,XMLSerializer 要求您的类具有默认构造函数(UserCollection 和 User 没有)并且每个类都必须具有 [Serializable] 属性。