Specifically as follows:
XML files: Files under the mydocument folder
Copy Code code as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<personf xmlns= "" Name= "(test) work hard work" >
<person name= "Person1" >
<ID>1</ID>
<Name>XiaoA</Name>
<Age>59</Age>
</person>
<person name= "Person2" >
<ID>2</ID>
<Name>XiaoB</Name>
<Age>29</Age>
</person>
<person name= "Person3" >
<ID>3</ID>
<Name>XiaoC</Name>
<Age>103</Age>
</person>
<person name= "Person4" >
<ID>4</ID>
<Name>XiaoD</Name>
<Age>59</Age>
</person>
</PersonF>
Code: The description is in the comment.
Copy Code code as follows:
void Testxml ()
{
XmlDocument doc = new XmlDocument ();
String path = "Http://www.jb51.net/MyDocument/Person.xml";
Try
{
Doc. Load (path);
1, read the data of a single node
XmlNode node = doc. selectSingleNode ("personf");
2. Read data from multiple nodes
XmlNodeList NodeList1 = doc. SelectNodes ("Personf/person");
3.1 Read the specific values of specific nodes such as: InnerText of the second node name of the Person2 property
XmlNodeList nodelist = doc. Documentelement.getelementsbytagname ("person");
foreach (XmlNode node2 in NodeList1)//Of course can also use nodelist value
{
if (Node2. attributes["Name"]. InnerText = = "Person2")
{
Console.WriteLine (Node2. CHILDNODES[1]. InnerText);
}
}
3.2 Read innertext with the second child node name of the node with ID 2
XmlNode node3 = doc. selectSingleNode ("personf/person[id=2]");
String strNode3 = Node3. CHILDNODES[1]. InnerText;
3.3 Use the following method to find the node with ID 2
XmlNodeList NodeList2 = doc. SelectNodes ("//person//id");
XmlNode node4 = null;
foreach (XmlNode node5 in NodeList2)
{
if (NODE5. InnerText = = "2")
{
Node4 = NODE5;
Break
}
}
Console.WriteLine (Node4. InnerText);
4, read the properties of the node
String Name = node. attributes["Name"]. InnerText;
5 Modifying the properties of a node
Node. attributes["Name"]. innertext = "Work hard work smart!";
Doc. Save (path);
6 Adding a custom node
XmlTextReader reader = new XmlTextReader (path);
XmlElement root = Doc. documentelement;//Get root node
XmlElement tagouter = doc. createelement ("person");
XmlElement tagin = doc. CreateElement ("Name");
Tagin.innertext = "Work hard work smart!";
Tagouter.appendchild (Tagin);
Root. AppendChild (tagouter);//Add Tagouter to the end of the XML file
Reader. Close ();
Doc. Save (path);
}
catch (System.Exception e)
{
throw new Exception (e.message);
}
}