這篇文章給大家分享的是有關XML如何寫一個xml序列化器的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
<span style="font-family:Microsoft YaHei;font-size:18px;">person p=new person() {Name = "istari", Age = 22, Email = "1061399756@qq.com"};</span>
<span style="font-family:Microsoft YaHei;font-size:18px;">MySerialize(p, typeof(person));</span>
<span style="font-family:Microsoft YaHei;font-size:18px;">private static void MySerialize(object obj, Type type) { //創建一個XDocument對象 XDocument document = new XDocument(); //寫入xml文件,把類名作為根節點 string nsStr = type.ToString(); string className = nsStr.Substring(nsStr.LastIndexOf('.') + 1); //寫入根節點 XElement rootElement = new XElement(className); //獲取當前類型中的所有的屬性 PropertyInfo[] properties = type.GetProperties(); //遍歷 foreach (PropertyInfo item in properties) { rootElement .SetElementValue (item.Name ,item.GetValue (obj,null)); } document .Add (rootElement ); document .Save (className +".xml"); }</span>
其中用到反射來獲取person類中的所有屬性。
<span style="font-family:Microsoft YaHei;font-size:18px;"><?xml version="1.0" encoding="utf-8"?> <person> <Name>istari</Name> <Age>22</Age> <Email>1061399756@qq.com</Email> </person></span>
感謝各位的閱讀!關于“XML如何寫一個xml序列化器”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。