如何在.net中实现动态部分XML类序列化

本文关键字:XML 序列化 动态部 实现 net | 更新日期: 2023-09-27 18:17:00

我喜欢使用默认的。net xml序列化器将数据保存为简单的xml格式。我有一个enum MemberCode { feild1 = 1, feild2 = 2 /*...*/}在运行时,我生成一个List<MemberCode>的成员,我想保存到xml(有时更多,有时更少)。

如何实现这样的部分类序列化?

如何在.net中实现动态部分XML类序列化

下面的代码可以解决您的问题。

创建一个可序列化的类MemberList,它包含一个MemberCodes数组。在运行时填充成员代码列表之后,我们将其转换为数组并将其序列化为XML。测试结果将被保存到debug文件夹中的test.xml文件中。

XML输出

<?xml version="1.0" encoding="utf-8"?>
    <MemberList xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Members>
        <Member>Field1</Member>
        <Member>Field2</Member>
        <Member>Field3</Member>
        <Member>Field2</Member>
        <Member>Field1</Member>
        <Member>field4</Member>
      </Members>
    </MemberList>

代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            // Your member code list
            List<MemberCode> list = new List<MemberCode>();
            // Add some members to the list during runtime (replace with your logic)
            list.Add(MemberCode.Field1);
            list.Add(MemberCode.Field2);
            list.Add(MemberCode.Field3);
            list.Add(MemberCode.Field2);
            list.Add(MemberCode.Field1);
            list.Add(MemberCode.field4);
            // Create a new serializable member list
            MemberList memberList = new MemberList();
            // Convert your list to a serializable array
            memberList.MemberCode = list.ToArray();
            // Write the XML to a file
            XmlSerializer serializer = new XmlSerializer(typeof(MemberList));
            TextWriter writer = new StreamWriter("test.xml");
            serializer.Serialize(writer, memberList);
            Console.ReadLine();
        }
    }
    [XmlRoot]
    public class MemberList
    {
        [XmlArray("Members")]
        [XmlArrayItem("Member", typeof(MemberCode))]
        public MemberCode[] MemberCode { get; set; }
    }
    public enum MemberCode
    {
        Field1 = 1,
        Field2 = 2,
        Field3 = 3,
        field4 = 4
    }
}