0

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

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

4

1 回答 1

0

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

我们创建了一个名为 MemberList 的可序列化类,其中包含一个 MemberCode 数组。在运行时填充您的成员代码列表后,我们将其转换为数组并将其序列化为 XML。结果将保存到调试文件夹中名为“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
    }
}
于 2013-06-06T04:00:42.147 回答