[DRP] Using dom4j to import XML files to the database

Source: Internet
Author: User
Xml files play an important role in current web development. From database connection configuration to other parameter settings, xml files play an important role in reflection technology applications, because the xml file contains such important parameters, the read and write operations on the xml file become more important. Next we will focus on dom4j to import XML files to the database.

Xml files play an important role in current web development. From database connection configuration to other parameter settings, xml files play an important role in reflection technology applications, because the xml file contains such important parameters, the read and write operations on the xml file become more important. Next we will focus on dom4j to import XML files to the database.


Xml files play an important role in current web development. From database connection configuration to other parameter settings, xml files play an important role in reflection technology applications, because the xml file contains such important parameters, the read and write operations on the xml file become more important. Next we will focus on dom4j to import XML files to the database.

0. The xml file with reading is as follows:


1. Use PL/SQL to import SQL scripts, and create an Oracle database table (table T_XML) structure to receive data imported from xml.

2. Follow the instructions to create a directory and import the corresponding files.

Through the introduction of jar package, implementation of dom4j technology to parse xml files (dom4j-1.6.1.jar, jaxen-1.1-Beta-6.jar and other jar packages ).


2.1 introduce files in lib to classpath

Test_xmlImport right-click properties -- Java Build Path -- Libraries -- Add External JARs


2.2. DbUtil. java contains:

Xml configuration file. The configuration file contains the driver name, service url, user name, and user password.

Database Connection and Shutdown

Transaction commit, rollback, reset

Package com. bjpowernode. xml; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement;/*** encapsulate Common Data Operations * @ author Administrator **/public class DbUtil {/*** get Connection * @ return */public static Connection getConnection () {Connection conn = null; try {// register the driver Class. forName ("oracle. jdbc. d River. oracleDriver "); // connection String (protocol name: jdbc, sub-protocol name: oracle: thin sub-Name: @ localhost: 1521: oracleDB) String url =" jdbc: oracle: thin: @ localhost: 1521: bjpowern "; String username =" drp1 "; String password =" drp1 "; // get the link conn = DriverManager. getConnection (url, username, password);} catch (ClassNotFoundException e) {e. printStackTrace ();} catch (SQLException e) {e. printStackTrace ();} return conn;} // close the database connection public static Void close (Connection conn) {if (conn! = Null) {try {conn. close ();} catch (SQLException e) {e. printStackTrace () ;}}// disable PreparedStatementpublic static void close (Statement pstmt) {if (pstmt! = Null) {try {pstmt. close ();} catch (SQLException e) {e. printStackTrace () ;}}// close the database connection public static void close (ResultSet rs) {if (rs! = Null) {try {rs. close ();} catch (SQLException e) {e. printStackTrace () ;}}// preparations before the start of the transaction, set to manually submit public static void beginTransaction (Connection conn) {try {if (conn! = Null) {if (conn. getAutoCommit () {conn. setAutoCommit (false); // manually submit }}} catch (SQLException e) {}} // submit the transaction public static void commitTransaction (Connection conn) {try {if (conn! = Null) {if (! Conn. getAutoCommit () {conn. commit () ;}} catch (SQLException e) {}} // rollback transaction public static void rollbackTransaction (Connection conn) {try {if (conn! = Null) {if (! Conn. getAutoCommit () {conn. rollback () ;}} catch (SQLException e) {}} // reset the database Connection and restore to the original state public static void resetConnection (Connection conn) {try {if (conn! = Null) {if (conn. getAutoCommit () {conn. setAutoCommit (false);} else {conn. setAutoCommit (true) ;}}catch (SQLException e) {}} public static void main (String [] args) {System. out. println (DbUtil. getConnection ());}}

2.3. The TestXMLImport class is used to read the information in the XML file and write it into the database table.
Package com. bjpowernode. xml; import java. io. file; import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. util. iterator; import java. util. list; import org. dom4j. document; import org. dom4j. element; import org. dom4j. io. SAXReader; public class TestXMLImport {/*** @ param args */public static void main (String [] args) {// SQL statement to import data to the database table T_XML String SQL = "insert T_XML (NUMERO, REPOSICION, NOMBRE, TURNOS) values (?, ?, ?, ?) "; Connection conn = null; PreparedStatement pstmt = null; try {conn = DbUtil. getConnection (); pstmt = conn. prepareStatement (SQL); // locate the location of the XML file to be read, Document doc = new SAXReader (). read (new File ("D:/share/JavaProjects/drp/test_xmlImport/xml/test01.XML"); // extract the content List itemList = doc of the specified node in the XML File. selectNodes ("/ACCESOS/item/SOCIO"); for (Iterator iter = itemList. iterator (); iter. hasNext ();) {Element el = (Element) I Ter. next (); String numero = el. elementText ("NUMERO"); String reposicion = el. elementText ("REPOSICION"); String nombre = el. elementText ("NOMBRE"); List turnosList = el. elements ("TURNOS"); StringBuffer sbString = new StringBuffer (); for (Iterator iter1 = turnosList. iterator (); iter1.hasNext ();) {Element turnosElt = (Element) iter1.next (); String lu = turnosElt. elementText ("LU"); String ma = turnosElt. elementTe Xt ("MA"); String mi = turnosElt. elementText ("MI"); String ju = turnosElt. elementText ("JU"); String vi = turnosElt. elementText ("VI"); String sa = turnosElt. elementText ("SA"); String doo = turnosElt. elementText ("DO"); sbString. append (lu + "," + ma + "," + mi + "," + ju + "," + vi + "," + sa + ", "+ doo);} pstmt. setString (1, numero); pstmt. setString (2, reposicion); pstmt. setString (3, nombre); pstmt. setString (4, SbString. toString (); // Add this execution statement to pstmt in the batch processing command of the PreparedStatement object. addBatch ();} // submit all the commands in the upload to batch command to the data warehouse to execute pstmt.exe cuteBatch (); System. out. println ("importing XML into the database succeeded! ");} Catch (Exception e) {e. printStackTrace () ;}finally {DbUtil. close (pstmt); DbUtil. close (conn );}}}

Discussion area:

(1) XPath is the XML Path language. It is a language used to determine a part of the XML document. The XML-based tree structure of XPath provides the ability to search nodes in the data structure tree.
The role of XPath is very similar to that of common SQL statements, except that SQL is used for database operations, while XPath is mainly used for searching and locating xml files.

(2) dom4j is an API used to read and write XML.
(3) Previously we used executeUpdate () when writing data to the database. In this article, we used addBatch (). What is the difference between them?

Pstmt. addBatch () loads Several SQL statements together and sends them to the database for execution once. Execution takes a short time.
Pstmt.exe cuteUpdate () is sent to the database for execution. The time is spent on the transmission of database connections.

Because the processing speed of the database is amazing. The single throughput is very large and the execution efficiency is extremely high. The larger the data volume, the more advantageous the former is.


This article introduces a common knowledge point: dom4j to import XML files to the database. At the end of the article, I briefly introduced some functions of XPath and dom4j. The differences between addBatch () and executeUpdate () are compared. Hope to help you.



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.