發布時間:2020-09-08 15:11 作者:獨孤劍 閱讀:3208
using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; namespace ConsoleApp34 { class Program { static void Main(string[] args) { Student student = new Student(); student.Name = "張三"; student.Age = "18"; // 序列化 string xml = XmlSerialize<Student>(student); /* <?xml version="1.0"?> <student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <name>張三</name> <age>18</age> </student> */ // 反序列化 Student xml2Model= XmlDeserialize<Student>(xml); } /// <summary> /// 序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string XmlSerialize<T>(T obj) { try { using (MemoryStream ms = new MemoryStream()) { XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(ms, obj); return Encoding.UTF8.GetString(ms.ToArray()); } } catch { throw; } } /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xml"></param> /// <returns></returns> public static T XmlDeserialize<T>(string xml) where T : class { try { using (StringReader sr = new StringReader(xml)) { XmlSerializer serializer = new XmlSerializer(typeof(T)); return serializer.Deserialize(sr) as T; } } catch { throw; } } } /// <summary> /// 學生 /// </summary> [XmlRoot("student")] public class Student { /// <summary> /// 姓名 /// </summary> [XmlElement(ElementName = "name")] public string Name { get; set; } /// <summary> /// 年齡 /// </summary> [XmlElement(ElementName = "age")] public string Age { get; set; } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞