Preface
. NET Framework XML class provides an XML analyzer object XmlDocument, which is the core object for most XML operations. When operating XML documents, you must first define an XmlDocument object, load the XML file into the memory, and then read and write the XML file.
Reading directory
1: Write an XML file
2: code file writing
Instance
How can we get the name, gender, and age we want?
Steps
1: Write an XML file
XMLFile. xml
<? Xml version = "1.0" encoding = "UTF-8"?>
<Students>
<Student>
<Name> Zhang San </name>
<Sex> male </sex>
<Age> 27 </age>
</Student>
<Student>
<Name> Luxi </name>
<Sex> female </sex>
<Age> 26 </age>
</Student>
</Students>
2: code file writing
Form1.cs
Using System. Data;
Using System. Drawing;
Using System. Text;
Using System. Windows. Forms;
Using System. Xml;
Namespace XmlDocumentClass
{
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}
Private void Form1_Load (object sender, EventArgs e)
{
// Declare an XmlDocument object
XmlDocument xml_doc = new XmlDocument ();
// Load the compiled XMLFile. xml file to the memory. Here you can use the relative address or absolute address. Here we use the relative address.
Xml_doc.Load ("XMLFile. xml ");
// The DocumentElement attribute indicates that the root node for obtaining the XML document will obtain the selected node SelectSingleNode ("/Students ") the method is to obtain the first XmlNode that matches the XPath expression query, that is, it will continue to obtain all the nodes under Students under the node I selected in the figure, and finally get the node I selected
XmlNode xml_node = xml_doc. DocumentElement. SelectSingleNode ("/Students ");
Figure 1
Figure 2
// Obtain information about Michael Jacob.
MessageBox. Show (xml_node.ChildNodes [0]. InnerText );
But if we only want the name "Zhang San", we can do this.
// Get a node set, that is, get the node information in Figure 3
XmlNodeList xml_node_list = xml_doc.DocumentElement.SelectNodes ("student ");
Figure 3
// Obtain the text information of the first child node
String strName = xml_node_list [0]. ChildNodes [0]. InnerText;
MessageBox. Show (strName );
}
}
}