zoukankan      html  css  js  c++  java
  • .NET对象的XML序列化和反序列化

     虽说是转的,不过之前还是说点自己的感受.最近被朋友拉去参加一个面向代理的程序设计竞赛,挺有意思的,类似面向服务,不过要求使用.NET平台,虽然以前用过,不过对.NET的理解实在没法跟JAVA比,不过越用越发现,落后的东西各有各的长处,先进的东西都是一样一样的,哈哈.真没想到,连JAXB在.NET里都有,本来还打算自己写个类似的类库呢,顿时对.NET好感倍增,现在JDBC也学.NET引入了类似DATASET,JAVA学引入了类似属性的注释类型,真的是越来越像的.反而到觉得,让两者区分的却存在于语言本身,而非类库.举个简单的例子,JAVA的类支持静态代码段,典型的设计模式上的应用就是JDBC利用这种机制实现了桥梁模式,而C#却不能,当然,我对专门针对.NET的设计模式并不了解,这不代表没法实现,就好比GOF的一些方法移到JAVA里就可以更简单的实现,或是JAVA语言本身就无法实现一样,语言给我们的只是代码级别的区别.而整体的思想大家却都一样,就好象这次的面向代理的运行容器也是从开源社区学JAVA的.大家的目的都是一样的,只是途径不通而已,各有长短而已.下面就是转的了,只为记录下,以后忘了能查,对MSDN实在没啥信心:
    (转).NET对象的XML序列化和反序列化
    一 概述
    .NET Framework为处理XML数据提供了许多不同的类库。XmlDocument类能让你像处理文件一样处理xml数据,而XmlReader、XmlWriter和它们的派生类使你能够将xml数据作为数据流处理。
    XmlSerializer则提供了另外的方法,它使你能够将自己的对象串行化和反串行化为xml。串行化数据既能够让你像处理文件一样对数据进行随机处理,同时又能跳过你不感兴趣的数据。
    二 主要类库介绍
       .NET 支持对象xml序列化和反序列化的类库主要位于命名空间System.Xml.Serialization中。
       1.  XmlSerializer 类
       该类用一种高度松散耦合的方式提供串行化服务。你的类不需要继承特别的基类,而且它们也不需要实现特别的接口。相反,你只需在你的类或者这些类的公共域以及读/写属性里加上自定义的特性。XmlSerializer通过反射机制读取这些特性并用它们将你的类和类成员映射到xml元素和属性。
       2. XmlAttributeAttribute 类
       指定类的公共域或读/写属性对应xml文件的Attribute。
       例:[XmlAttribute(“type”)] or [XmlAttribute(AttributeName=”type”)]
       3. XmlElementAttribute类
       指定类的公共域或读/写属性对应xml文件的Element。
       例:[XmlElement(“Maufacturer”)] or [XmlElement(ElementName=”Manufacturer”)]
       4. XmlRootAttribute类
       Xml序列化时,由该特性指定的元素将被序列化成xml的根元素。
       例:[XmlRoot(“RootElement”)] or [XmlRoot(ElementName = “RootElements”)]
       5. XmlTextAttribute 类
       Xml序列化时,由该特性指定的元素值将被序列化成xml元素的值。一个类只允许拥有一个该特性类的实例,因为xml元素只能有一个值。
       6. XmlIgnoreAttribute类
       Xml序列化时不会序列化该特性指定的元素。
    三 实例
       下面例子中的xml schema 描述了一个简单的人力资源信息,其中包含了xml的大部分格式,如xml 元素相互嵌套, xml元素既有元素值,又有属性值。
       1. 待序列化的类层次结构
        [XmlRoot("humanResource")]
        public class HumanResource
        {
            #region private data.
            private int m_record = 0;
            private Worker[] m_workers = null;
            #endregion
     
            [XmlAttribute(AttributeName="record")]
            public int Record
            {
                get { return m_record; }
                set { m_record = value; }
            }
     
            [XmlElement(ElementName="worker")]
            public Worker[] Workers
            {
                get { return m_workers; }
                set { m_workers = value; }
            }
    }
     
        public class Worker
        {
            #region private data.
            private string m_number = null;
            private InformationItem[] m_infoItems = null;
            #endregion
     
            [XmlAttribute("number")]
            public string Number
            {
                get { return m_number; }
                set { m_number = value; }
            }
     
            [XmlElement("infoItem")]
            public InformationItem[] InfoItems
            {
                get { return m_infoItems; }
                set { m_infoItems = value; }
            }
    }
     
        public class InformationItem
        {
            #region private data.
            private string m_name = null;
            private string m_value = null;
            #endregion
     
            [XmlAttribute(AttributeName = "name")]
            public string Name
            {
                get { return m_name; }
                set { m_name = value; }
            }
     
            [XmlText]
            public string Value
            {
                get { return m_value; }
                set { m_value = value; }
            }
    }
       2. 序列化生成的xml结构
           <?xml version="1.0" ?>
    - <humanResource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" record="2">
    - <worker number="001">
                     <infoItem name="name">Michale</infoItem>
                     <infoItem name="sex">male</infoItem>
                     <infoItem name="age">25</infoItem>
                </worker>
    - <worker number="002">
                     <infoItem name="name">Surce</infoItem>
                     <infoItem name="sex">male</infoItem>
                     <infoItem name="age">28</infoItem>
               </worker>
             </humanResource>
       3. 利用XmlSerializer类进行序列化和反序列化的实现(一般利用缓存机制实现xml文件只解析一次。)
        public sealed class ConfigurationManager
        {
            private static HumanResource m_humanResource = null;
            private ConfigurationManager(){}
     
            public static HumanResource Get(string path)
            {
                if (m_humanResource == null)
                {
                    FileStream fs = null;
                    try
                    {
                        XmlSerializer xs = new XmlSerializer(typeof(HumanResource));
                        fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                        m_humanResource = (HumanResource)xs.Deserialize(fs);
                        fs.Close();
                        return m_humanResource;
                    }
                    catch
                    {
                        if (fs != null)
                            fs.Close();
                        throw new Exception("Xml deserialization failed!");
                    }
     
                }
                else
                {
                    return m_humanResource;
                }
            }
     
            public static void Set(string path, HumanResource humanResource)
            {
                if (humanResource == null)
                    throw new Exception("Parameter humanResource is null!");
               
                FileStream fs = null;
                try
                {
                    XmlSerializer xs = new XmlSerializer(typeof(HumanResource));
                    fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                    xs.Serialize(fs, humanResource);
                    m_humanResource = null;
                    fs.Close();
                }
                catch
                {
                    if (fs != null)
                        fs.Close();
                    throw new Exception("Xml serialization failed!");
                }
            }
        }
    四 说明
       1. 需要序列化为xml元素的属性必须为读/写属性;
       2. 注意为类成员设定缺省值,尽管这并不是必须的。
     

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dongchengok/archive/2007/04/22/1574496.aspx

  • 相关阅读:
    c语言结构体数组引用
    c语言结构体数组定义的三种方式
    如何为SAP WebIDE开发扩展(Extension),并部署到SAP云平台上
    SAP SRM ABAP Webdynpro和CFCA usb key集成的一个原型开发
    使用SAP API portal进行SAP SuccessFactors的API测试
    SAP UI5应用里的页面路由处理
    在SAP WebIDE Database Explorer里操作hdi实例
    如何使用SAP事务码SAT进行UI应用的性能分析
    使用SAP WebIDE进行SAP Cloud Platform Business Application开发
    SAP CRM WebClient UI ON_NEW_FOCUS的用途
  • 原文地址:https://www.cnblogs.com/voidxy/p/1520641.html
Copyright © 2011-2022 走看看