[Java project practice] dom4j parses xml files, connects to the Oracle database, and dom4joracle
Introduction
Dom4j is an open source XML parsing package produced by dom4j.org. This sentence is too official. Let's take a look at the official explanation. For example:
Dom4j is an easy-to-use, open-source library for parsing XML, XPath, XSLT, and other languages. It is applied to the Java platform and adopts the Java Collection framework and fully supports DOM, SAX, JAXP and other programming standards.
Features
Dom4j is a very good Java xml api with excellent performance, powerful functionality and extreme ease of use. It is also an open source software. Now you can see that more and more Java software are using dom4j to read and write XML, such as Hibernate, and sun's own JAXM also uses dom4j.
Download
Since dom4j has more than N advantages, we must unveil the secrets of dom4j. To use dom4j for development, download the corresponding jar file of dom4j.
1. Official download: http://www.dom4j.org/dom4j-1.6.1/
2. dom4j is an open-source project on sourceforge.net. You can download the latest version from http://sourceforge.net/projects/dom4j.
Open the unzipping file of the dom4j-1.6.1, and we can see a folder with the help of docs, and a dom4j-1.6.1.jar file that dom4j parses the xml file. We only need to build the dom4j-1.6.1.jar file into our development project, you can use dom4j development.
Instance
Below we use dom4j to read the system configuration file to connect to the Oracle database. Before starting, build the jar we need into our project, for example:
1. Copy Oracle jdbc driver to WEB-INF/lib
2. Copy the jar related to dom4j to the WEB-INF/lib.
(1) dom4j-1.6.1.jar
(2) jaxen-1.1-beta-6.jar (supporting xpath-related jar packages)
Database Connection class: DbUitl. java
Package util; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. SQLException; public class DbUtil {/*** get Connection * @ return */public static Connection getConnection () {Connection conn = null; try {JdbcConfig jdbcConfig = XmlConfigReader. getInstance (). getJdbcConfig (); // obtain the path Class of the oracle driver. forName (jdbcConfig. getDriverName (); // String url = "jdbc: oracle: thin: @ MyDbComputerNameOrIP: 1521: ORCL"; // database connection. oracle indicates connecting to the oracle database; thin: @ MyDbComputerNameOrIP indicates the IP address of the database (thin can be retained :); // 1521 indicates the port number to connect to the database; ORCL indicates the database name conn = DriverManager. getConnection (jdbcConfig. getUrl (), jdbcConfig. getUserName (), jdbcConfig. getPassword ();} catch (ClassNotFoundException e) {e. printStackTrace ();} catch (SQLException e) {e. printStackTrace () ;}return conn ;}}
Database profile: sys-config.xml
<?xml version="1.0" encoding="UTF-8"?><config><db-info><driver-name>oracle.jdbc.driver.OracleDriver</driver-name><url>jdbc:oracle:thin:@localhost:1521:oracle</url><user-name>drp1</user-name><password>drp1</password></db-info></config>
Jdbc configuration: JdbcConfig. java
Package util;/*** jdbc configuration information ** @ author liang **/public class JdbcConfig {private String driverName; private String url; private String userName; private String password; public String getDriverName () {return driverName;} public void setDriverName (String driverName) {this. driverName = driverName;} public String getUrl () {return url;} public void setUrl (String url) {this. url = url;} public String getUserName () {return userName;} public void setUserName (String userName) {this. userName = userName;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password ;}}
Dom4j reads xml: XmlConfigReader. java
Package util; import java. io. inputStream; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader;/*** resolve the sys-config.xml file with a single example * @ author liang **/public class XmlConfigReader {// example lazy (delayed loading lazy) // set to null, use in new, do not use newprivate static XmlConfigReader instance = null; // define JdbcConfig member variables, save jdbc-related configuration information private JdbcConfig jdbcConfig = new JdbcConfig (); private XmlConfigReader () {// create the saxReader object SAXReader reader = new SAXReader (); // obtain the relative path of the file through the class loader of the current thread, read the xml file into the input stream InputStream in = Thread. currentThread (). getContextClassLoader (). getResourceAsStream ("sys-config.xml"); try {// read the xml file through the read method and convert it to the Document Object Document doc = reader. read (in); // obtain the Node object and obtain the jdbc-related configuration information Element driverNameElt = (Element) doc. selectObject ("/config/db-info/driver-name"); Element urlElt = (Element) doc. selectObject ("/config/db-info/url"); Element userNameElt = (Element) doc. selectObject ("/config/db-info/user-name"); Element passwordElt = (Element) doc. selectObject ("/config/db-info/password"); // set jdbc-related configuration jdbcConfig. setDriverName (driverNameElt. getStringValue (); jdbcConfig. setUrl (urlElt. getStringValue (); jdbcConfig. setUserName (userNameElt. getStringValue (); jdbcConfig. setPassword (passwordElt. getStringValue ();} catch (incluentexception e) {e. printStackTrace () ;}} public static synchronized XmlConfigReader getInstance () {if (instance = null) {instance = new XmlConfigReader ();} return instance ;} /*** return jdbc configuration * @ return */public JdbcConfig getJdbcConfig () {return jdbcConfig ;}}
Parsing: Reading and Writing XML documents mainly depends on the org. dom4j. io package, which provides two different methods: DOMReader and SAXReader, and the call method is the same. This is the benefit of relying on interfaces.
The reader's read method is overloaded and can be read from multiple sources such as InputStream, File, and Url. The resulting Document object represents the entire XML.
Step 4 of dom4j parsing xml
1. Create a SAXReader object in singleton Mode
2. Read the xml file into the input stream
3. read the xml file using the read method and convert it into a document object.
4. Get the node value of the xml file through the document Object
Summary
As the saying goes: standing on the shoulders of giants. Dom4j is a giant. it is OK to have a clear understanding of dom4j and use it.
Supports source code download: dom4j parses xml and connects to the oracle database
Generate xml from the oracle database query data, and insert the data in the xml file parsed by java to the oracle database in batches (using SAX for parsing)
I asked if I had something to write before.
The database creates a table study.
Id student class teacher age five fields
Package com. SQL. xml;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. FileWriter;
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. ResultSet;
Import java. SQL. Statement;
Import org. dom4j. Document;
Import org. dom4j. DocumentHelper;
Import org. dom4j. Element;
Import org. dom4j. io. OutputFormat;
Import org. dom4j. io. XMLWriter;
// Export data into XML
Public class ReadDb {
Public static void main (String args []) {
// Connect to the database
Try {
// Database connection
String url = "jdbc: oracle: thin: @ 10.0.3.18: 1521: hxtest18 ";
String classforname = "oracle. jdbc. driver. OracleDriver ";
String usename = "zhiyong ";
String password = "password ";
Class. forName (classforname );
Connection con = DriverManager. getConnection (url, usename, password );
Statement sta = con. createStatement ();
// Query data
ResultSet result=sta.exe cuteQuery (
"SELECT * FROM study ");
// Create the root node
Document document = incluenthelper. createDocument ();
Element studyInfo = incluenthelper. createElement ("studyInfo ");
Document. setRootElement (studyInfo );
// Element studyInfo = document. addElement ("studyInfo ");
// Query when a value exists
While (result. next ()){
// Add each node
Element study = studyInfo. addElement ("study ");
Element id = study. addElement (& ...... remaining full text>
An error occurred while parsing the XML file in JAVA Dom4j.
The error occurs because the element or attribute does not match.
<Offers xmlns: = ""> can there be a colon after the xmlns attribute?
Are you sure this xml document is correct? That is, each group of tags is paired?
You can send the xml file to me. In the past two days, we have finished a huge xml parsing job with dom4j...