C# XML 序列化


代码

[XmlRootAttribute("CustomerMappings")]
public class CustomerMappings
{
    [XmlArray("Mappings")]
    public List<CustomerMapping> Mappings { get; set; }
}

public class CustomerMapping
{
    [XmlAttribute]
    public string ColumnName { get; set; }

    [XmlAttribute]
    public string MappingName { get; set; }
}

    public sealed class XmlSerializerHelper
{
    private static object obj = new object();

    public static bool Serialize<T>(T model, string fileName) 
    {
        try
        {
            lock (obj)
            {
                using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    //得到被序列化的类型
                    Type type = model.GetType();
                    XmlSerializer sz = new XmlSerializer(type);
                    //开始序列化
                    sz.Serialize(stream, model);
                    sz.Serialize(Console.Out, model);
                }
            }
        }
        catch (Exception ex)
        {

        }

        return true;
    }

    public static T Deserialize<T>(string fileName)
    {
        T t = default(T);
        try
        {
            lock (obj)
            {
                using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    //得到被序列化的类型
                    Type type = typeof(T);
                    XmlSerializer sz = new XmlSerializer(type);
                    //开始序列化
                    t = (T)sz.Deserialize(stream);
                }
            }
        }
        catch (Exception ex)
        {

        }

        return t;
    }

}

生成的 XML 文件

<?xml version="1.0"?>
<CustomerMappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Mappings>
    <CustomerMapping ColumnName="Customer" MappingName="Customer" />
    <CustomerMapping ColumnName="TypeofBusiness" MappingName="2" />
    <CustomerMapping ColumnName="Name" MappingName="3" />
    <CustomerMapping ColumnName="Name2" MappingName="4" />
    <CustomerMapping ColumnName="City" MappingName="5" />
    <CustomerMapping ColumnName="Street" MappingName="6" />
    <CustomerMapping ColumnName="PostlCode" MappingName="7" />
    <CustomerMapping ColumnName="Telephone" MappingName="8" />
    <CustomerMapping ColumnName="Region" MappingName="9" />
    <CustomerMapping ColumnName="SubRegion" MappingName="10" />
    <CustomerMapping ColumnName="Province" MappingName="11" />
    <CustomerMapping ColumnName="Prov" MappingName="12" />
    <CustomerMapping ColumnName="LocationId" MappingName="13" />
  </Mappings>
</CustomerMappings>
站内公告

A PHP Error was encountered

Severity: Core Warning

Message: PHP Startup: zip: Unable to initialize module Module compiled with module API=20060613 PHP compiled with module API=20090626 These options need to match

Filename: Unknown

Line Number: 0

Backtrace: