Let's take a look at the use of XML in C #.
In fact, an XML file will exist in the form of a DOM tree after being added to the memory,
Therefore, operations on an XML file are ultimately an operation on the Dom,
First, let's take a look at the general structure of the XML file.
That is, a student in a school has a student ID, name, gender, and age.
<? XML version = "1.0" encoding = "UTF-8"?>
<School>
<Student number = "001">
<Name> Xiaozhen </Name>
<Sex> male </sex>
<Age> 20 </age>
</Student>
<Student number = "002">
<Name> baobei </Name>
<Sex> male </sex>
<Age> 20 </age>
</Student>
<Student number = "003">
<Name> Suha </Name>
<Sex> female </sex>
<Age> 21 </age>
</Student>
<Student number = "004">
<Name> baobeime </Name>
<Sex> female </sex>
<Age> 20 </age>
</Student>
</School>
Then the basic operation is performed on it.
Public class getallxmldata
{
Private string xmlpath;
Public getallxmldata (string path)
{
Xmlpath = path;
}
// Obtain all data in the XML file of the specified path
// Return the dataset as a dataview object
Public dataview getxmldataview ()
{
Datatable mytable = new datatable ();
Datarow myrow;
Mytable. Columns. Add ("student ID", type. GetType ("system. String "));
Mytable. Columns. Add ("name", type. GetType ("system. String "));
Mytable. Columns. Add ("gender", type. GetType ("system. String "));
Mytable. Columns. Add ("Age", type. GetType ("system. String "));
Xmldocument xmldoc = new xmldocument ();
Xmldoc. Load (xmlpath );
Xmlelement root = xmldoc. documentelement;
Foreach (xmlnode node in root. childnodes)
{
Myrow = mytable. newrow ();
Myrow ["student ID"] = node. attributes ["Number"]. value;
Myrow ["name"] = node. selectsinglenode ("./Name"). innertext;
Myrow ["gender"] = node. selectsinglenode ("./sex"). innertext;
Myrow ["Age"] = node. selectsinglenode ("./age"). innertext;
Mytable. Rows. Add (myrow );
}
Return mytable. defaultview;
}
}
Another example is to add a new data entry to the XML file.
Public void insertxmldata (string xmlpath)
{
Xmldocument xmldoc = new xmldocument ();
Xmldoc. Load (xmlpath );
Xmlelement root = xmldoc. documentelement;
Xmlelement student = xmldoc. createelement ("student ");
Student. setattribute ("Number", strnumber );
Xmlelement name = xmldoc. createelement ("name ");
Name. innertext = strname;
Xmlelement sex = xmldoc. createelement ("sex ");
Sex. innertext = strsex;
Xmlelement age = xmldoc. createelement ("Age ");
Age. innertext = strage;
Student. appendchild (name );
Student. appendchild (sex );
Student. appendchild (AGE );
Root. appendchild (student );
Xmldoc. Save (xmlpath );
}
From aboveCodeWe can see that
An XML operation is fully implemented in the form of Dom.
The key to understanding XML is Dom.