Java and XML (2): Use dom4j to operate XML files

Source: Internet
Author: User

1. dom4j Introduction

Dom4j is an open-source framework for parsing XML files. It supports local XPath, but does not support selecting nodes using XPath.

Although dom4j represents completely independent development results, it was originally a smart branch of JDOM. It combines many functions beyond the representation of basic XML documents, including integrated XPath support, XML Schema support, and event-based processing for large or streaming documents. It also provides the option to build document representation. It provides parallel access through the dom4j API and standard DOM interface. It has been under development since the second half of 2000. To support all these functions, dom4j uses interfaces and abstract basic class methods. Dom4j uses a large number of collections classes in the API, but in many cases, it also provides alternative methods to allow better performance or more direct encoding methods. The direct advantage is that although dom4j pays for more complex APIs, it provides much greater flexibility than JDOM. When adding flexibility, XPath integration, and processing large documents, dom4j has the same goals as JDOM: ease of use and intuitive operations for Java developers. It is also committed to becoming a more complete solution than JDOM to achieve the goal of essentially handling all Java/XML problems. When this goal is achieved, it places less emphasis on preventing incorrect application behavior than JDOM. Dom4j is a very good Java xml api with excellent performance, powerful functionality and extreme ease of use features. 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. It is particularly worth mentioning that Sun's jaxm is also using dom4j.

Main Methods:

  • Createdocument
  • Addelement
  • Settext

2. Use dom4j to generate xml files

Test A small instance: Use dom4j to create an XML file

ImportJava. Io. filewriter;

ImportOrg. dom4j. Document;
ImportOrg. dom4j. extends enthelper;
ImportOrg. dom4j. element;
ImportOrg. dom4j. Io. xmlwriter;

/**
* @ Author: Hu Jiawei
* @ Createtime: 11:14:11
* @ Description:
*/

Public ClassDom4jxml {

Public Static VoidMain (string [] ARGs ){
Dom4jxml dom4j =NewDom4jxml ();
Dom4j. generatedocument ();
}

Public VoidGeneratedocument (){
Document document = incluenthelper. createdocument ();
Element bookselement = Document. addelement ("books ");
Bookselement. addcomment ("a Java book ");
Element bookelement = bookselement. addelement ("book ");
Bookelement. addattrir ("author", "yinger ");
Element nameelement = bookelement. addelement ("name ");
Nameelement. settext ("Java notebook ");
Element priceelement = bookelement. addelement ("price ");
Priceelement. settext ("10.00 RMB ");

Try{
Xmlwriter outwriter =NewXmlwriter (NewFilewriter ("books. xml "));
Outwriter. Write (document );
Outwriter. Close ();
}Catch(Exception e ){
E. printstacktrace ();
}
}

}

Display Effect of the generated file in IE:

3. Example: export the table content in the database to an XML file

ImportJava. Io. filewriter;
ImportJava. SQL. connection;
ImportJava. SQL. drivermanager;
ImportJava. SQL. resultset;
ImportJava. SQL. resultsetmetadata;
ImportJava. SQL. statement;

ImportOrg. dom4j. Document;
ImportOrg. dom4j. extends enthelper;
ImportOrg. dom4j. element;
ImportOrg. dom4j. Io. xmlwriter;

/**
* @ Author: Hu Jiawei
* @ Createtime: 11:39:14
* @ Description: store data in the database to an XML file.
*/

Public ClassDbxml {

Public Static VoidMain (string [] ARGs ){
Dbxml =NewDbxml ();
Dbxml. db2xml2 ();
}

/**
* This method requires the name of each column in the database.
*/
Public BooleanDb2xml (){
Try{
Class. forname ("org. gjt. Mm. MySQL. Driver"). newinstance ();
String url = "JDBC: mysql: // localhost/blog? User = root & Password = root ";
Connection connection = drivermanager. getconnection (URL); // Note: connection is Java. SQL. Connection
Statement statement = connection. createstatement ();
String SQL = "select * from blog ";
Resultset rs = statement.exe cutequery (SQL );

Document document = incluenthelper. createdocument ();
Element rootelement = Document. addelement ("blogs ");

While(Rs. Next ()){
Element blogeelement = rootelement. addelement ("blog ");
Blogeelement. addattribute ("ID", Rs. getstring ("ID "));
Element cidelement = blogeelement. addelement ("categoryid ");
Cidelement. settext (Rs. getstring ("categoryid "));
Element titleelement = blogeelement. addelement ("title ");
Titleelement. settext (Rs. getstring ("title "));
Element contentelement = blogeelement. addelement ("content ");
Contentelement. settext (Rs. getstring ("content "));
Element timeelement = blogeelement. addelement ("createtime ");
Timeelement. settext (Rs. getstring ("created_time "));
}
Rs. Close ();

Xmlwriter =NewXmlwriter (NewFilewriter ("blogs. xml "));
Xmlwriter. Write (document );
Xmlwriter. Close ();

ReturnTrue;
}Catch(Exception e ){
E. printstacktrace ();
ReturnFalse;
}
}

/**
* This method is not required. It uses resultsetmetadata
*/
Public BooleanDb2xml2 (){
Try{
Class. forname ("org. gjt. Mm. MySQL. Driver"). newinstance ();
String url = "JDBC: mysql: // localhost/blog? User = root & Password = root ";
Connection connection = drivermanager. getconnection (URL); // Note: connection is Java. SQL. Connection
Statement statement = connection. createstatement ();
String SQL = "select * from blog ";
Resultset rs = statement.exe cutequery (SQL );
Resultsetmetadata rsmd = Rs. getmetadata ();
IntCols = rsmd. getcolumncount ();

Document document = incluenthelper. createdocument ();
Element rootelement = Document. addelement ("blogs ");

While(Rs. Next ()){
Element blogeelement = rootelement. addelement ("blog ");
For(IntI = 1; I <Cols; I ++) {// note, here I starts from 1!
Element element = blogeelement. addelement (rsmd. getcolumnname (I ));
Element. settext (Rs. getstring (I ));
}
}
Rs. Close ();

Xmlwriter =NewXmlwriter (NewFilewriter ("blogs2.xml "));
Xmlwriter. Write (document );
Xmlwriter. Close ();

ReturnTrue;
}Catch(Exception e ){
E. printstacktrace ();
ReturnFalse;
}
}

}

Result Display: Data in the blog table

Method 1: ID is an attribute

Method 2: ID is a child element node.

 

Publish via wiz

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.