首页 > 代码库 > C#对象序列化成XML,以及自定义标签名
C#对象序列化成XML,以及自定义标签名
C#对象序列化操作:
public class XMLHelper{ /// <summary> /// 对象序列化成 XML String /// </summary> public static string XmlSerialize<T>(T obj) { string xmlString = string.Empty; XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); //using (TextWriter textWriter = new StreamWriter("D:\\xmlTest.xml")) //{ // xmlSerializer.Serialize(textWriter, obj); //} using (MemoryStream ms = new MemoryStream()) { xmlSerializer.Serialize(ms, obj); xmlString = Encoding.UTF8.GetString(ms.ToArray()); } return xmlString; } /// <summary> /// XML String 反序列化成对象 /// </summary> public static T XmlDeserialize<T>(string xmlString) { T t = default(T); XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString))) { using (XmlReader xmlReader = XmlReader.Create(xmlStream)) { Object obj = xmlSerializer.Deserialize(xmlReader); t = (T)obj; } } return t; }}
示例:
[Serializable][XmlType(TypeName = "MySong")]public class Song{ [XmlElement("A")] public string Artist; [XmlElement("S")] public string SongTitle;}class XMLDemo{ static void Main(string[] args) { List<Song> list = new List<Song>() { new Song(){ SongTitle="歌曲标题1",Artist="歌手1"}, new Song(){ SongTitle="歌曲标题2",Artist="歌手2"}, new Song(){ SongTitle="歌曲标题3",Artist="歌手3"} }; string xmlString = XMLHelper.XmlSerialize(list); /*<?xml version="1.0"?> <ArrayOfSong xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Song> <Artist>歌手1</Artist> <SongTitle>歌曲标题1</SongTitle> </Song> <Song> <Artist>歌手2</Artist> <SongTitle>歌曲标题2</SongTitle> </Song> <Song> <Artist>歌手3</Artist> <SongTitle>歌曲标题3</SongTitle> </Song> </ArrayOfSong> // 自定义标签名 <?xml version="1.0"?> <ArrayOfMySong xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <MySong> <A>歌手1</A> <S>歌曲标题1</S> </MySong> <MySong> <A>歌手2</A> <S>歌曲标题2</S> </MySong> <MySong> <A>歌手3</A> <S>歌曲标题3</S> </MySong> </ArrayOfMySong> */ Console.WriteLine(xmlString); }}
C#对象序列化成XML,以及自定义标签名
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。