. Net XML creation 01 (traditional method),. netxml
Traditional XML creation:
The traditional creation is based on the XmlDocument object. The XmlDocument object can be used to create elements (XmlElement), attributes (XmlAttribute), and text nodes (CreateTextNode)
Specific instance:
XML:
1-> Create an XmlDocument and description, and add the description:
XmlDocument xml = new XmlDocument ();
XmlDeclaration xmldec = xmlDoc. CreateXmlDeclaration ("1.0", "gb2312", null );
Xml. AppendChild (xmldec );
2-> Create a root node and add it to xml. Only one root node can exist.
XmlElement root = xml. CreateElement ("root ");
Xml. AppendChild (root );
3-> prepare the data, loop through the data set, and create the XmlElement element node and Its Related
List <Student> list = new List <Student> (){
New Student () {Name = "James", Gender = "male", Age = 17 },
New Student () {Name = "", Gender = "male", Age = 21 },
New Student () {Name = "Wang Wu", Gender = "male", Age = 19}
};
// Objects in the method set
For (int I = 0; I <list. Count (); I ++)
{
// Create an stu node and add the property id
XmlElement stu = xml. CreateElement ("Student"); // create an element using XmlDocument's instance xml
XmlAttribute id = xml. CreateAttribute ("id"); // you can use the XmlDocument instance xml to create an attribute.
Id. Value = "00" + (I + 1); // assign a Value to the attribute
Stu. Attributes. Append (id); // Add the attribute id to the attribute set of stu.
// Create and copy the name node. Then append it to the stu node.
XmlElement name = xml. CreateElement ("Name"); // use the XmlDocument instance xml to create elements
Name. AppendChild (xml. CreateTextNode (list [I]. Name); // creates a TextNode for the element and assigns a value
Stu. AppendChild (name); // Add the name node to the stu Node
// Create and copy the age node. Then append it to the stu node.
XmlElement age = xml. CreateElement ("Age ");
Age. AppendChild (xml. CreateTextNode (list [I]. Age. ToString ()));
Stu. AppendChild (age );
// Create and copy a gender node. Then append it to the stu node.
XmlElement gender = xml. CreateElement ("Gender ");
Gender. AppendChild (xml. CreateTextNode (list [I]. Gender ));
Stu. AppendChild (gender );
// Append the stu node to the root node
Root. AppendChild (stu );
}
4-> Save the XML file
Xml. Save ("xxx. xml ");
5-> the final generated XML
<? Xml version = "1.0" encoding = "gb2312"?>
<Root>
<Student id = "001">
<Name> Zhang San </Name>
<Age> 17 </Age>
<Gender> male </Gender>
</Student>
<Student id = "002">
<Name> Li Si </Name>
<Age> 21 </Age>
<Gender> male </Gender>
</Student>
<Student id = "003">
Name> Wang Wu </Name>
<Age> 19 </Age>
<Gender> male </Gender>
</Student>
</Root>