XML is applied to many aspects of web development and is often used to simplify the storage and sharing of data, and it is designed to transmit data rather than display it. Here's a brief look at how C # reads the XML file.
1. First, create an XML object and associate an XML file
string " Student.xml " New XmlDocument (); Xmldoc.load (xmlfilename);
2. Gets the root node of the XML file
// gets the root node of the XML file XmlElement noderoot = xmldoc.documentelement;
3. Create a new node
//Create a new nodeXmlElement nodenew = xmldoc.createelement ("Student");//Create a child node for a new nodeXmlElement Nodenum = xmldoc.createelement ("Num"); XmlElement NodeName= Xmldoc.createelement ("name"); XmlElement Nodeage= Xmldoc.createelement (" Age");//establish a parent-child relationship between the Children node and the new nodeNodenew.appendchild (Nodenum); Nodenew.appendchild (nodeName); Nodenew.appendchild (nodeage) ;//Create the node text and associate the nodeXmlText Txtnum = Xmldoc.createtextnode ("001"); XmlText txtname= Xmldoc.createtextnode ("Zhang San"); XmlText txtage= Xmldoc.createtextnode (" A"); Nodenum.appendchild (Txtnum); Nodename.appendchild (txtname); Nodeage.appendchild (txtage) ;
4. Add new node to file
// Add the newly created node noderoot.appendchild (nodenew); // Add to root node // Noderoot.insertbefore (nodenew, noderoot.firstchild); // Add to Trailer
5. Deleting nodes
if (noderoot.haschildnodes) { noderoot.removechild (noderoot.firstchild); // Delete First node }
6. Traversing nodes
//Traverse Student.xml To view the age value of the specified nodeXmlNodeList studentlist = Noderoot.selectnodes ("*");foreach(XmlNode Studentinchstudentlist) { if(Student. FirstChild.InnerText.Equals ("004") {XmlNodeList stuchidnodelist= student. SelectNodes ("*"); foreach(XmlNode Stuchilenodeinchstuchidnodelist) { if(StuChileNode.Name.Equals (" Age") {console.write (Stuchilenode.innertext+" "); }} Console.WriteLine (); Break; } Else { Continue; } }
7. Save the XML file
// Save XMLXmldoc.save (XMLfileName);
Attachment:
Experimental XML file (student.xml)
<?XML version= "1.0" encoding= "Utf-8"?><!--Student root Node -<Students> <Studentclass= "Clss1"> <Num>002</Num> <name>Hello2</name> < Age>22</ Age> </Student> <Studentclass= "Clss2"> <Num>003</Num> <name>Hello3</name> < Age>88</ Age> </Student> <Student> <Num>004</Num> <name>Faf</name> < Age>43</ Age> </Student> <Student> <Num>005</Num> <name>New</name> < Age>22</ Age> </Student> <Student> <Num>006</Num> <name>New</name> < Age>22</ Age> </Student> <Student> <Num>001</Num> <name>Tom</name> < Age>22</ Age> </Student> <Student> <Num>001</Num> <name>Tom</name> < Age>22</ Age> </Student></Students>
Student.xml
RELATED links:
XML Basics Tutorial: http://www.w3school.com.cn/xml/index.asp
XML file Operations (C #)