This paper mainly introduces the knowledge of C # reading and writing XML, which has a good reference value. Let's take a look at the little series.
Read XML
XmlDocument xd = new XmlDocument (); String fileName = @ "D:\test.xml"; Xd. Load (fileName); XmlNodeList xmlnotelist = xd. getElementsByTagName ("user"); list<user> users = new list<user> (); foreach (XmlElement item in xmlnotelist) { User user = new User (); User. Id = Int. Parse (item. GetAttribute ("id")); XmlNodeList XNL = Item. ChildNodes; User. Name = xnl[0]. InnerXml; User. Age =int. Parse (Xnl[1]. INNERXML); User. Gender = xnl[2]. InnerXml; Users. ADD (user); } foreach (var item in users) { Console.WriteLine (item); } Read XML
<?xml version= "1.0" encoding= "gb2312"?><users> <user id= ' 1 ' > <name > Zhang San </name > <age>15</age> <gender> men </gender> </user> <user id= ' 2 ' > <name> John Doe </name> <age>14</age> <gender> men </gender> </ User></users>test.xml
Write XML
String FileName =@ "D:\test.xml"; XmlDocument xmldoc = new XmlDocument (); XmlNode Header = xmldoc.createxmldeclaration ("1.0", "Utf-8", null); Xmldoc.appendchild (header); Create a first-level node XmlElement RootNode = Xmldoc.createelement ("users"); list<user> list = Getusers (); foreach (var item in list) {XmlElement xn = inseruser (item,xmldoc); Rootnode.appendchild (xn); } xmldoc.appendchild (RootNode); Xmldoc.save (FileName); }///<summary>//Create an entire user element///</summary>//<param name= "user" ></param>// <param name= "xmldoc" ></param>//<returns></returns> private static XmlElement Inseruser (Us Er user, XmlDocument xmldoc) {XmlElement xn = xmldoc.createelement ("user"); Xn. SetAttribute ("id", user.) Id + ""); Xn. AppendChild (Getxmlnode (xmldoc, "name", user. Name)); Xn. AppendChild (Getxmlnode (xmldoc, "age", user. Age + "")); Xn. AppendChild(Getxmlnode (xmldoc, "Gender", user.) Gender)); return xn; } private static XmlElement Getxmlnode (XmlDocument xmldoc,string name,string value) {XmlElement xn = xmldoc.cr Eateelement (name); Xn. InnerText = value; return xn; } private static List<user> getusers () {list<user> List = new list<user> (); for (int i = 0; i < i++) {User user = new User (); User. Id = i; User. Name = "name" + i; User. age = 15; User. Gender = "male"; List. ADD (user); } return list; }write XML
Entity class
Class User {public int Id {set; get;} public string Name {get; set;} public int Age {get; set;} public string Gender {set; get;} public override string ToString () { return Id + "," +name + "," +age+ "," + Gender; } } Entity