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 }
  • 相关阅读:
    从内存中加载并启动一个exe
    使用Hamcrest增强JUnit的测试能力
    Delphi编译指令说明
    Delphi 64与32位的差异
    获取exe文件窗口抓图,将memo转化为JPG输出
    Delphi 的 Utf-8 转换
    我的第一个破解软件,试验成功!
    Qt之QComboBox(基本应用、代理设置)
    常见寄存器以及常见汇编指令,常见爆破指令 good
    大神级回答exists与in的区别
  • 原文地址:https://www.cnblogs.com/servant/p/4462446.html
Copyright © 2011-2022 走看看