序列化(一):XMLSerilize

http://www.codeproject.com/KB/XML/Serialization_Samples.aspx
如果类实现了IDictionary,就不能被序列化。如:Hashtables cannot be serialized.
  • By using XML serialization only public properties and fields can be serialized. If private members are to be serialized, other serialization methods should be used.
  • It requires a parameterless constructor. This constructor is called during deserialization.
  • Serialized form of the object does not contain any type, assembly information of the class. Only the data is stored.
  • Using XML serialization not all the classes can be serialized. Classes that implement IDictionary cannot be serialized. E.g. Hashtables cannot be serialized. Arrays of objects can be easily serialized. Collections can be serialized but to serialize collections certain rules must be followed.
  • Null values are not serialized with XML serialization. To include the null members in the serialized form IsNullable attribute should be set to true. For example:
  • [ XmlElement( IsNullable = true ) ]
    去掉xmlns:
    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
    namespaces.Add(
    string.Empty, string.Empty);            
    serializer.Serialize(writer, source, namespaces);
    改变根元素的名字:RootName
    XmlRootAttribute root = new XmlRootAttribute();
    root.ElementName 
    = name;
    XmlSerializer xs 
    = new XmlSerializer(typeof(T), root);
    格式化序列化类中嵌套类的属性:

     [XmlArrayItem(Type=typeof(NetAtt),ElementName="item")]
        
    public List<NetAtt> NetAtts;

    你也可以自定义XMLTextWriter 去掉XML Declaration.<?xml version="1.0" encoding="utf-8" ?>
    public class SpecialXmlWriter : XmlTextWriter
    {
        
    bool m_includeStartDocument = true;
        
    public SpecialXmlWriter(TextWriter tw, bool includeStartDocument)
            : 
    base(tw)
        {
            m_includeStartDocument 
    = includeStartDocument;
        }
        
    public SpecialXmlWriter(Stream sw, Encoding encoding, bool includeStartDocument)
            : 
    base(sw, null)
        {
            m_includeStartDocument 
    = includeStartDocument;
        }
        
    public SpecialXmlWriter(string filePath, Encoding encoding, bool includeStartDocument)
            : 
    base(filePath, null)
        {
            m_includeStartDocument 
    = includeStartDocument;
        }
        
    public override void WriteStartDocument()
        {
            
    if (m_includeStartDocument)
            {
                
    base.WriteStartDocument();
            }
        }
    }
    测试如下:

    XmlSerializer serializer = null;
            SpecialXmlWriter swriter 
    = null;
            
    try
            {
                serializer 
    = new XmlSerializer(objXml.GetType());
                swriter 
    = new SpecialXmlWriter(Server.MapPath("~/a.xml"), System.Text.Encoding.Default, false);
                
    if (!isNameSpaces)
                {
                    XmlSerializerNamespaces xNamesSpace 
    = new XmlSerializerNamespaces();
                    xNamesSpace.Add(
    """");
                    serializer.Serialize(swriter, objXml, xNamesSpace);
                }
                
    else
                    serializer.Serialize(swriter, objXml);
            }
            
    catch (Exception ex)
            {
                
    throw new Exception(ex.ToString());
            }
            
    finally
            {
                
    if (swriter != null)
                {
                    swriter.Close();
                }
            }
    //
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Xml.Serialization;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Xml;
    public partial class Default2 : System.Web.UI.Page
    {
        
    protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        
    protected void Button1_Click(object sender, EventArgs e)
        {
            List
    <GaryPerson> objlist = new List<GaryPerson>(){
             
    new GaryPerson{ strPassword="张三", strUserName="P"}
            };
            Serialize(objlist, Server.MapPath(
    "~/obj.xml"));
             
        }
        
    void Serialize(object source, string file)
        {
            XmlWriterSettings settings 
    = new XmlWriterSettings();
            settings.OmitXmlDeclaration 
    = true;
            settings.Indent 
    = true;
             
            
    using (XmlWriter writer = XmlWriter.Create(file, settings))
            {
                XmlRootAttribute root 
    = new XmlRootAttribute("GaryList");
                XmlSerializer serializer 
    = new XmlSerializer(source.GetType(),root);
               
                XmlSerializerNamespaces namespaces 
    = new XmlSerializerNamespaces();
                namespaces.Add(
    string.Empty, string.Empty);
                 
                serializer.Serialize(writer, source, namespaces);
            }
        }
        
    }
    [Serializable]
    public class GaryPerson
    {
        
    public string strUserName;
        
    public string strPassword;
    }

    posted on 2009-09-03 17:11  博览潇湘  阅读(559)  评论(0)    收藏  举报

    导航