zoukankan      html  css  js  c++  java
  • 通过XmlSerializer 实现XML的序列化与反序列化

    通过XmlSerializer 我们可以十分简单的将Model与XML进行转换

    官文在点这里

    帮助类

      1 using System;
      2 using System.Text;
      3 using System.Xml.Serialization;
      4 using System.IO;
      5 using System.Xml;
      6 
      7 namespace BLL
      8 {
      9     public class XmlHelper
     10     {
     11         public static T DeSerializeModels<T>(string XMLStr, string eleName)
     12         {
     13             XmlRootAttribute Root = new XmlRootAttribute();
     14             Root.ElementName = eleName;
     15 
     16             XmlSerializer xs = new XmlSerializer(typeof(T), Root);
     17 
     18             StringReader strReader = new StringReader(XMLStr);
     19             System.Xml.XmlReader r = new System.Xml.XmlTextReader(strReader);
     20             try
     21             {
     22                 T Result = (T)xs.Deserialize(r);
     23                 return Result;
     24             }
     25             finally
     26             {
     27                 strReader.Close();
     28                 r.Close();
     29             }
     30         }
     31 
     32         public static string SerializeModels<T>(T Models,string eleName)
     33         {
     34             StringBuilder sb = new StringBuilder();
     35             StringWriter w = new StringWriter(sb);
     36 
     37             XmlRootAttribute Root = new XmlRootAttribute();
     38             Root.ElementName = eleName;
     39 
     40             XmlSerializer sr = new XmlSerializer(typeof(T), Root);
     41             sr.Serialize(w, Models);
     42 
     43             w.Close();
     44 
     45             return sb.ToString();
     46         }
     47 
     48         private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
     49         {
     50             if (o == null)
     51                 throw new ArgumentNullException("o");
     52             if (encoding == null)
     53                 throw new ArgumentNullException("encoding");
     54 
     55             XmlSerializer serializer = new XmlSerializer(o.GetType());
     56 
     57             XmlWriterSettings settings = new XmlWriterSettings();
     58             settings.Indent = true;
     59             settings.NewLineChars = "
    ";
     60             settings.Encoding = encoding;
     61             settings.IndentChars = "    ";
     62 
     63             using (XmlWriter writer = XmlWriter.Create(stream, settings))
     64             {
     65                 serializer.Serialize(writer, o);
     66                 writer.Close();
     67             }
     68         }
     69 
     70         /// <summary>
     71         /// 将一个对象序列化为XML字符串
     72         /// </summary>
     73         /// <param name="o">要序列化的对象</param>
     74         /// <param name="encoding">编码方式</param>
     75         /// <returns>序列化产生的XML字符串</returns>
     76         public static string XmlSerialize(object o, Encoding encoding)
     77         {
     78             using (MemoryStream stream = new MemoryStream())
     79             {
     80                 XmlSerializeInternal(stream, o, encoding);
     81 
     82                 stream.Position = 0;
     83                 using (StreamReader reader = new StreamReader(stream, encoding))
     84                 {
     85                     return reader.ReadToEnd();
     86                 }
     87             }
     88         }
     89 
     90         /// <summary>
     91         /// 将一个对象序列化为XML字符串
     92         /// </summary>
     93         /// <param name="o">要序列化的对象</param>
     94         /// <returns>序列化产生的XML字符串</returns>
     95         public static string XmlSerialize(object o)
     96         {
     97             return XmlSerialize(o, Encoding.UTF8);
     98         }
     99 
    100         /// <summary>
    101         /// 将一个对象按XML序列化的方式写入到一个文件
    102         /// </summary>
    103         /// <param name="o">要序列化的对象</param>
    104         /// <param name="UploadPath">保存文件路径</param>
    105         /// <param name="encoding">编码方式</param>
    106         public static void XmlSerializeToFile(object o, string path, Encoding encoding)
    107         {
    108             if (string.IsNullOrEmpty(path))
    109                 throw new ArgumentNullException("path");
    110 
    111             using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
    112             {
    113                 XmlSerializeInternal(file, o, encoding);
    114             }
    115         }
    116 
    117         /// <summary>
    118         /// 将一个对象按XML序列化的方式写入到一个文件
    119         /// </summary>
    120         /// <param name="o">要序列化的对象</param>
    121         /// <param name="UploadPath">保存文件路径</param>
    122         public static void XmlSerializeToFile(object o, string path)
    123         {
    124             XmlSerializeToFile(o, path, Encoding.UTF8);
    125         }
    126 
    127         /// <summary>
    128         /// 从XML字符串中反序列化对象
    129         /// </summary>
    130         /// <typeparam name="T">结果对象类型</typeparam>
    131         /// <param name="s">包含对象的XML字符串</param>
    132         /// <param name="encoding">编码方式</param>
    133         /// <returns>反序列化得到的对象</returns>
    134         public static T XmlDeserialize<T>(string s, Encoding encoding)
    135         {
    136             if (string.IsNullOrEmpty(s))
    137                 throw new ArgumentNullException("s");
    138             if (encoding == null)
    139                 throw new ArgumentNullException("encoding");
    140 
    141             XmlSerializer xs = new XmlSerializer(typeof(T));
    142             using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
    143             {
    144                 using (StreamReader sr = new StreamReader(ms, encoding))
    145                 {
    146                     return (T)xs.Deserialize(sr);
    147                 }
    148             }
    149         }
    150 
    151         /// <summary>
    152         /// 从XML字符串中反序列化对象
    153         /// </summary>
    154         /// <typeparam name="T">结果对象类型</typeparam>
    155         /// <param name="s">包含对象的XML字符串</param>
    156         /// <returns>反序列化得到的对象</returns>
    157         public static T XmlDeserialize<T>(string s)
    158         {
    159             return XmlDeserialize<T>(s, Encoding.UTF8);
    160         }
    161 
    162         /// <summary>
    163         /// 读入一个文件,并按XML的方式反序列化对象。
    164         /// </summary>
    165         /// <typeparam name="T">结果对象类型</typeparam>
    166         /// <param name="UploadPath">文件路径</param>
    167         /// <param name="encoding">编码方式</param>
    168         /// <returns>反序列化得到的对象</returns>
    169         public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
    170         {
    171             if (string.IsNullOrEmpty(path))
    172                 throw new ArgumentNullException("path");
    173             if (encoding == null)
    174                 throw new ArgumentNullException("encoding");
    175 
    176             string xml = File.ReadAllText(path, encoding);
    177             return XmlDeserialize<T>(xml, encoding);
    178         }
    179 
    180         /// <summary>
    181         /// 读入一个文件,并按XML的方式反序列化对象。
    182         /// </summary>
    183         /// <typeparam name="T">结果对象类型</typeparam>
    184         /// <param name="UploadPath">文件路径</param>
    185         /// <returns>反序列化得到的对象</returns>
    186         public static T XmlDeserializeFromFile<T>(string path)
    187         {
    188             return XmlDeserializeFromFile<T>(path, Encoding.UTF8);
    189         }
    190     }
    191 }
    工具类

    同时也可以通过设置Model的特性,灵活的控制序列化

    using System.Xml.Serialization;
    using System;
    using System.Collections.Generic;
    
    namespace Model
    {
        /// <summary>
        /// 节点名是EleTeacher
        /// </summary>
        [Serializable]
        [XmlType("EleTeacher")]
        public class Teacher
        {
            [XmlElement(ElementName = "user")]
            public string AuthorID { set; get; }
    
            [XmlIgnore]
            public string Content { set; get; }
    
            [XmlText]
            public string Value { set; get; }
    
            [XmlArray("students")]
            public List<Student> sds { set; get; }
        }
    
        [Serializable]
        public class Student
        {
            [XmlAttribute(AttributeName = "id")]
            public string ID { set; get; }
    
            [XmlText]
            public string Name { set; get; }
        }
    }
    Model
  • 相关阅读:
    Docker最全教程之MySQL容器化 (二十四)
    Docker最全教程之使用Node.js搭建团队技术文档站(二十三)
    Docker最全教程之使用PHP搭建个人博客站点(二十二)
    构建自己的简单微服务架构(开源)
    使用Jmeter进行http接口测试
    Appium 服务关键字
    Appium入门示例(Java)
    Appium for win7 环境搭建
    android adb常用指令
    Android测试环境搭建(win7)
  • 原文地址:https://www.cnblogs.com/TiestoRay/p/2880857.html
Copyright © 2011-2022 走看看