Document directory
I have previously written an article on XML search using XPath. Today, I wrote an example of operating XML files in a common way, which is also required by a netizen known by Baidu.
Suppose there are the following XML files:
<? XML version = "1.0" encoding = "UTF-8"?> <Users> <user code = "lm"> <Name> Dawn </Name> <sex> male </sex> <age> 28 </age> </user> <user code = "SQ"> <Name> Shu Qi </Name> <sex> female </sex> <age> 27 </age> </user> </users>
To import the above XML content to an Access database's userinfo table, the structure of the access userinfo table is as follows:
The Code is as follows:
// Replace the path of the Access database with the actual path using (oledbconnection Cn = new oledbconnection (@ "provider = Microsoft. jet. oledb.4.0; Data Source = D: \ demo. mdb ") {CN. open (); Using (oledbcommand cmd = new oledbcommand () {cmd. connection = cn; cmd. commandtype = commandtype. text; xmldocument xml = new xmldocument (); // Replace the XML path with the actual path XML. load (@ "D: \ demo. XML "); // get all userxmlnodelist xn = xml. getelementsbytagname ("user"); // traverses all userforeach (xmlelement Xe in XN) {cmd. commandtext = string. format ("insert into userinfo ([usercode], [username], [usersex], [userage]) values ('{0}', '{1 }', '{2}', {3}) ", Xe. getattribute ("Code"), // get codexe. childnodes [0]. innertext, // obtain namexe. childnodes [1]. innertext, // obtain sexxe. childnodes [2]. innertext // get age); // insert data cmd. executenonquery ();}}}