| The code is as follows |
Copy Code |
| XmlDocument xmldoc = new XmlDocument (); Add XML declaration paragraph at the top of XML document XmlNode XmlNode = xmldoc. CreateNode (Xmlnodetype.xmldeclaration, "", ""); XmlDoc. AppendChild (XmlNode); To create a root node XmlElement root = xmldoc. createelement ("root"); Root. innertext = "I am the root node"; XmlDoc. AppendChild (root); XmlDoc. Save (@ "D:my documentsvisual Studio 2010projectswebapplication2webapplication2test.xml"); |
The resulting XML is like this
| The code is as follows |
Copy Code |
<?xml version= "1.0"?> <root> I am the root node </root> |
Another way to create XML
| The code is as follows |
Copy Code |
XmlDocument xmldoc = new XmlDocument (); XmlDoc. Loadxml ( "<?xml version=" 1.0 "encoding=" Utf-8 "?>" + "<root> I am the root node </root>" ); XmlDoc. Save (@ "D:my documentsvisual Studio 2010projectswebapplication2webapplication2test.xml"); |
Reading XML
XML is as follows
| The code is as follows |
Copy Code |
| <?xml version= "1.0" encoding= "Utf-8"?> <root id= "root" > <list num= "0" > <name type= "string" >minglecun</name> <age type= "Number" >55</age> </list> <list num= "1" > <name type= "string" >huluwa</name> <age type= "Number" >1</age> </list> </root> XmlDocument xmldoc = new XmlDocument (); XmlDoc. Load (@ "D:my documentsvisual Studio 2010projectswebapplication2webapplication2test.xml"); Read a node XmlNode XmlNode = xmldoc. selectSingleNode ("//root"); Console.WriteLine (XmlNode. INNERXML); Console.WriteLine ("------------------------------------------------"); XmlNode xmlnode1 = xmldoc. selectSingleNode ("//root//list"); Console.WriteLine (Xmlnode1. INNERXML); Console.WriteLine ("------------------------------------------------"); // XmlNodeList Xn0 = xmldoc. selectSingleNode ("//root"). ChildNodes; foreach (XmlNode node in xn0) { Console.WriteLine ("========" +node). Name); } |