C # operating xml files,

Source: Internet
Author: User

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 );
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.