当前位置: 移动技术网 > IT编程>开发语言>.net > XML操作类

XML操作类

2018年10月17日  | 移动技术网IT编程  | 我要评论

基金频道酷基金网,刘芳专辑,恶少 别惹我

 1 using system;
 2 using system.collections.generic;
 3 using system.io;
 4 using system.reflection;
 5 using system.text;
 6 using system.xml;
 7 
 8 namespace commonlib
 9 {
10     public class xmlhelper
11     {
12         public xmlhelper()
13         {
14 
15         }
16 
17         public void create<t>(string xmlpath, list<t> updatexmls)
18         {
19             xmldocument document = new xmldocument();
20             type type = typeof(t);
21             document.appendchild(document.createxmldeclaration("1.0", "utf-8", null));
22             xmlelement root = document.createelement(type.name + "collection");
23             propertyinfo[] properties = type.getproperties();
24             foreach (var updatexml in updatexmls)
25             {
26                 xmlelement parentelememt = document.createelement(type.name);
27                 foreach (propertyinfo property in properties)
28                 {
29                     xmlelement element = document.createelement(property.name);
30                     element.innertext = updatexml.getpropertyvalue(property).tostring();
31                     parentelememt.appendchild(element);
32                 }
33                 root.appendchild(parentelememt);
34             }
35             document.appendchild(root);
36             document.save(xmlpath);
37         }
38 
39         public list<t> read<t>(string updatexml) where t : new()
40         {
41             xmldocument document = new xmldocument();
42             document.load(updatexml);
43             list<t> tlist = new list<t>();
44             foreach (xmlnode node in document.childnodes[1].childnodes)
45             {
46                 t t = new t();
47                 foreach (xmlnode childnode in node.childnodes)
48                 {
49                     t.setpropertyvalue(childnode.name, childnode.innertext);
50                 }
51                 tlist.add(t);
52             }
53             return tlist;
54         }
55 
56 
57         public list<t> readcontext<t>(string context) where t : new()
58         {
59             xmldocument document = new xmldocument();
60             byte[] bytes = encoding.utf8.getbytes(context);
61             memorystream ms = new memorystream(bytes);
62             ms.seek(0, seekorigin.begin);
63             document.load(ms);
64             list<t> tlist = new list<t>();
65             foreach (xmlnode node in document.childnodes[1].childnodes)
66             {
67                 t t = new t();
68                 foreach (xmlnode childnode in node.childnodes)
69                 {
70                     t.setpropertyvalue(childnode.name, childnode.innertext);
71                 }
72                 tlist.add(t);
73             }
74             return tlist;
75         }
76     }
77 }

生成与对象一致的xml

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网