C summary of XML basic operation code

  • 2020-05-07 20:16:52
  • OfStack

The details are as follows:
XML files: the files are in the MyDocument folder
 
<?xml version="1.0" encoding="utf-8"?> 
<PersonF xmlns="" Name="(test)work hard work smart!"> 
<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 instructions are in the notes.
 
void TestXML() 
{ 
XmlDocument doc = new XmlDocument(); 
string path = "//www.ofstack.com/MyDocument/Person.xml"; 
try 
{ 
doc.Load(path); 
//1 , read the data of a single node  
XmlNode node = doc.SelectSingleNode("PersonF"); 
//2 , read the data of multiple nodes  
XmlNodeList nodeList1 = doc.SelectNodes("PersonF/person"); 
//3.1  Reads the specific value of the specific node   The property is Person2 The first 2 A node Name the InnerText 
XmlNodeList nodeList = doc.DocumentElement.GetElementsByTagName("person"); 
foreach (XmlNode node2 in nodeList1) // Of course it works nodeList The value of the  
{ 
if (node2.Attributes["Name"].InnerText == "Person2") 
{ 
Console.WriteLine(node2.ChildNodes[1].InnerText); 
} 
} 
//3.2  read ID for 2 The node is number one 2 Child node Name the InnerText 
XmlNode node3 = doc.SelectSingleNode("PersonF/person[ID=2]"); 
string strNode3 = node3.ChildNodes[1].InnerText; 
//3.3 It can be found using the following method ID for 2 The nodes of the  
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  Modify the properties of the node  
node.Attributes["Name"].InnerText = "work hard work smart!"; 
doc.Save(path); 
//6  Add custom nodes  
XmlTextReader reader = new XmlTextReader(path); 
XmlElement root = doc.DocumentElement;// Get the 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 XML End of file  
reader.Close(); 
doc.Save(path); 
} 
catch (System.Exception e) 
{ 
throw new Exception(e.Message); 
} 
} 

Related articles: