C # operating xml files,
Using System;
Using System. Collections. Generic;
Using System. Data;
Using System. Linq;
Using System. Text;
Using System. Threading. Tasks;
Using System. Xml;
Namespace delegatedemo
{
Public class XmlClass
{
Private string xmlPath;
Public XmlClass (string xmlPath)
{
This. xmlPath = xmlPath;
}
Public DataView GetXmlElement ()
{
DataTable myTable = new DataTable ();
DataRow myRow;
MyTable. Columns. Add ("student ID ");
MyTable. Columns. Add ("name ");
MyTable. Columns. Add ("Age ");
MyTable. Columns. Add ("gender ");
XmlDocument doc = new XmlDocument ();
Doc. Load (xmlPath );
XmlElement xmlElement = doc. DocumentElement;
Foreach (XmlNode node in xmlElement. ChildNodes)
{
String number = node. Attributes ["number"]. Value;
String age = node. SelectSingleNode ("Age"). InnerText;
String name = node. SelectSingleNode ("Name"). InnerText;
String sex = node. SelectSingleNode ("Sex"). InnerText;
MyRow = myTable. NewRow ();
MyRow ["student ID"] = number;
MyRow ["name"] = name;
MyRow ["gender"] = sex;
MyRow ["age"] = age;
MyTable. Rows. Add (myRow );
}
Return myTable. DefaultView;
}
Public void InsertXml ()
{
XmlDocument doc = new XmlDocument ();
Doc. Load (xmlPath );
XmlElement root = doc. DocumentElement;
XmlElement student = doc. CreateElement ("student ");
Student. SetAttribute ("number", "003 ");
XmlElement name = doc. CreateElement ("name ");
Name. InnerText = "James ";
XmlElement age = doc. CreateElement ("age ");
Age. InnerText = "21 ";
XmlElement sex = doc. CreateElement ("sex ");
Sex. InnerText = "female ";
Root. AppendChild (student );
Root. AppendChild (name );
Root. AppendChild (age );
Root. AppendChild (sex );
Doc. Save (xmlPath );
}
}
}