zoukankan      html  css  js  c++  java
  • C# XML与对象互相转换

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 using System.Xml.Serialization;
     5 using System.IO;
     6 using System.Xml;
     7 
     8 namespace Common
     9 {
    10     public class XmlUtility
    11     {
    12         /// <summary>
    13         /// 将自定义对象序列化为XML字符串
    14         /// </summary>
    15         /// <param name="myObject">自定义对象实体</param>
    16         /// <returns>序列化后的XML字符串</returns>
    17         public static string SerializeToXml<T>(T myObject)
    18         {
    19             if (myObject != null)
    20             {
    21                 XmlSerializer xs = new XmlSerializer(typeof(T));
    22 
    23                 MemoryStream stream = new MemoryStream();
    24                 XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
    25                 writer.Formatting = Formatting.None;//缩进
    26                 xs.Serialize(writer, myObject);
    27 
    28                 stream.Position = 0;
    29                 StringBuilder sb = new StringBuilder();
    30                 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    31                 {
    32                     string line;
    33                     while ((line = reader.ReadLine()) != null)
    34                     {
    35                         sb.Append(line);
    36                     }
    37                     reader.Close();
    38                 }
    39                 writer.Close();
    40                 return sb.ToString();
    41             }
    42             return string.Empty;
    43         }
    44 
    45         /// <summary>
    46         /// 将XML字符串反序列化为对象
    47         /// </summary>
    48         /// <typeparam name="T">对象类型</typeparam>
    49         /// <param name="xml">XML字符</param>
    50         /// <returns></returns>
    51         public static T DeserializeToObject<T>(string xml)
    52         {
    53             T myObject;
    54             XmlSerializer serializer = new XmlSerializer(typeof(T));
    55             StringReader reader = new StringReader(xml);
    56             myObject = (T)serializer.Deserialize(reader);
    57             reader.Close();
    58             return myObject;
    59         }
    60     }
    61 }
  • 相关阅读:
    Windows环境下Unicode编程总结
    我的CS脚本autoexec.cfg
    完成端口与高性能服务器程序开发[引用]
    调用未知DLL中的导出函数
    兼容Vista 赛门铁克公测新杀毒软件
    I Love You的真正含义
    码根码
    木马经典十大藏身地点大搜查
    Windows调试器及不同平台符号包下载地址(收集)
    “千般路”与“磨豆腐”
  • 原文地址:https://www.cnblogs.com/servant/p/4462446.html
Copyright © 2011-2022 走看看