C # import XML to the Access Database

Source: Internet
Author: User
Document directory
  • The Code is as follows:

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

 
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.