When designing a program, you can save some highly variable data in an XML file for ease of modification. Especially for some software and hardware configuration files, many choose to use XML files for access. XML files are easy to use and can read and write data in any application. Therefore, XML files are an important generic file. The following example shows how to create, read, and write an XML file.
Using command in XmlProcess class
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. IO;
Using System. Xml;
XmlProcess class
Class XmlProcess
{
// Create an XML Object
XmlDocument xmlDoc;
// Define a Node object
XmlNode node;
// Obtain the current working directory path
String workDir = Directory. GetCurrentDirectory ();
List <Student> stuList = new List <Student> ();
// Define an element
XmlElement xmlEle;
Public void CreatNewXml ()
{
// Create an XML file in the working directory
// Instantiate an XML Object
XmlDoc = new XmlDocument ();
// Add the Declaration section of the XML file, <? Xml version = "1.0" encoding = "gb2312"?>
XmlDeclaration xmlDecl;
XmlDecl = xmlDoc. CreateXmlDeclaration ("1.0", "gb2312", null );
XmlDoc. AppendChild (xmlDecl );
// Add a root element
XmlEle = xmlDoc. CreateElement ("", "External table ","");
XmlDoc. AppendChild (xmlEle );
// Obtain the root node
XmlNode root = xmlDoc. SelectSingleNode ("orders table ");
// Add a student record
XmlElement stu1 = xmlDoc. CreateElement ("Student 1 ");
XmlElement stuNo = xmlDoc. CreateElement ("student ID ");
StuNo. InnerText = "1001 ";
XmlElement stuName = xmlDoc. CreateElement ("name ");
StuName. InnerText = "abc ";
XmlElement stuGrade = xmlDoc. CreateElement ("score ");
StuGrade. InnerText = "96 ";
Stu1.AppendChild (stuNo );
Stu1.AppendChild (stuName );
Stu1.AppendChild (stuGrade );
Root. AppendChild (stu1 );
// Add the second student record
XmlElement stu2 = xmlDoc. CreateElement ("Student 2 ");
StuNo = xmlDoc. CreateElement ("student ID ");
StuNo. InnerText = "1002 ";
StuName = xmlDoc. CreateElement ("name ");
StuName. InnerText = "abcd ";
StuGrade = xmlDoc. CreateElement ("score ");
StuGrade. InnerText = "90 ";
Stu2.AppendChild (stuNo );
Stu2.AppendChild (stuName );
Stu2.AppendChild (stuGrade );
Root. AppendChild (stu2 );
// The preceding method is used to manually add an XML file. It is used to create and write an XML file.
// You can also use the XmlTextWriter object to output data streams.
// Generate and save the XML file