The previous article has introduced writing content into xml files through serializers. Here we still use the person class to write.
<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>
Used in Reflection to get all properties in person class.
<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>
The above is the content of XML (6) Write an xml serializer yourself, more For related content, please pay attention to the PHP Chinese website (www.php.cn)!