Java Dom4j reading XML

Source: Internet
Author: User
Tags xml parser xslt

In the past, I used less xml, but I only learned a lot about it. Now I can use it in DRP. I used to simply understand xml, xml can be used to expand the markup language. What is it? How to use it? I still keep making myself look forward to it.


First, let's take a look at the powerful functions of xml.


1. compatibility with existing Protocols

Management information in XML document format can be easily transmitted over HTTP. Because HTTP is built on TCP, management data can be reliably transmitted. XML also supports standard APIs for accessing XML documents, such as DOM, SAX, XSLT, and Xpath.

2. Unified management Data Access format

XML can define the structure of management information in a flexible and effective manner. The data stored in XML format not only has a good internal structure, but also is supported by the majority of software providers because it is an international standard proposed by W3C and is easy to exchange and develop data. The Management Information Library specifications of existing network management standards such as TMN and SNMP determine that the network management data conforms to the hierarchical structure and object-oriented principles, which makes it easy to store network management data in XML format.


3. data sharing and interaction between different application systems

Define a set of XML languages that describe various management data and management functions, define the language with Schema, and the XML documents of the systems that share the data follow these schemas, the data management and management functions can be shared and interacted between multiple application systems.

4. Data transmitted at the underlying layer is more readable

The underlying data transmitted in the network has different encoding rules due to different protocols. Although the underlying data is binary streams during transmission, different application protocols need to provide different conversion mechanisms. This makes it difficult for the management site to manage managed objects that use different protocols to send management information. If the protocol is described in XML format when the data is expressed, a simple pipeline stream is transmitted between networks. You can use the same XML parser to parse the protocol and then tag it based on different XML, differentiate different parts of the data to make the underlying data more readable. [4]



5. Both json and json are data exchange formats.

Data sharing between different databases and systems solves a big problem. systems developed in different languages can also use xml to share data;

Xml can, of course, store data in database tables because it has a certain structure, nodes, layers, and regularity. In this way, we can transfer data back and forth using xml for implementation ......


Since the role of xml is so important, how to parse xml and database data to generate xml is the primary solution, in order to flexibly retrieve database addresses, user names, and passwords through xml, it is clear that the system can be easily maintained and modified later.

What is Dom4j?

Dom4j is an easy-to-use, open-source library that works with XML, XPath, and XSLT on the Java platform. The Java Collection framework fully supports DOM, SAX, and JAXP.

Dom4j is a Java XMLAPI, similar to jdom, used to read and write XML files. Dom4j is a very good JavaXMLAPI with excellent performance, powerful functionality, and extreme ease of use. It is also an open source software that can be found on SourceForge.


Dom4j instance parsing XML
Xml file to read resolution: 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:@127.0.0.1:1521:ORCL</url><user-name>sys</user-name><password>sys</password></db-info></config>


Class for reading xml files: XmlConfigReader. java


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.
Import java. io. inputStream; // reference the corresponding package import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader;


Java class for reading xml: XmlConfigReader
In the code, the reader's read method is overloaded and can be read through different parameters such as InputStream, File, Url, and so on. An object is generated in singleton mode, and this object is instantiated as a SAXReader, then load the xml file into the stream. Then, use the read () method of SAXReader to convert it into a document object. Then, the document object is used to get the node value of the xml file.


Package conn. lishehe. drp. util; import java. io. inputStream; // reference the corresponding package import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader; public class XmlConfigReader {// lazy private static XmlConfigReader instance = null; // private JdbcConfig jdbcConfig = new JdbcConfig () for saving jdbc-related configuration information; private XmlConfigReader () {// create a SAXReader object SAXReader reader = new SAXRea Der (); // obtain the relative path of the file through the class loader of the current Thread, and read the buffer input stream InputStream in = Thread. currentThread (). getContextClassLoader (). getResourceAsStream ("sys-config.xml"); try {// get jdbc-related configuration information // read the xml file Document doc = reader through the stream. read (in); // read jdbc-related information // Element: used to describe elements in the XML document. 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");/* String driverName = driverNameElt. getStringValue (); String url = urlElt. getStringValue (); String userName = userNameElt. getStringValue (); @ SuppressWarnings ("unused") String password = passwordElt. getStringValue (); System. out. println (driverName); * // gets jdbc-related configuration jdbcConfig. setDriverName (driverNameElt. getStringValue (); jdbcConfig. setUrl (urlElt. getStringValue (); jdbcConfig. setUserName (userNameElt. getStringValue (); jdbcConfig. setPassword (passwordElt. getStringValue ();} catch (incluentexception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public static synchronized XmlConfigReader getInstance () {if (instance = null) {instance = new XmlConfigReader ();} return instance ;} /*** return jdbc configuration * @ return */public JdbcConfig getJdbcConfig () {return jdbcConfig;} public static void main (String [] args) {JdbcConfig jdbcConfig = XmlConfigReader. getInstance (). getJdbcConfig ();/* System. out. println (jdbcConfig. getDriverName (); System. out. println (jdbcConfig. getUrl (); System. out. println (jdbcConfig. getUserName (); */System. out. println (jdbcConfig );}}

Class of the defined object set: JdbcConfig. java

package conn.lishehe.drp.util;/** * Jdbc * @author lishe * */public class JdbcConfig {private String driverName;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;}private String url;private String userName;private String password;@Overridepublic String toString() {return this.getClass().getCanonicalName() + "{driverName:" + driverName + ", url:" + url + ", userName:" + userName + "}";}}

Data Processing Layer: DbUtil. java
Package conn. lishehe. drp. util; import java. SQL. connection; import java. SQL. driverManager; /*** encapsulate Common Database Operations ** @ author Li shehe */public class DbUtil {/*** get Connection * @ return * @ throws ClassNotFoundException */public static Connection getConnection () throws ClassNotFoundException {/* Connection conn = null; try {Class. forName ("oracle. jdbc. driver. oracleDriver "); String url =" jdbc: oracle: thin: @ 127.0.0.1: 1521: ORCL "; String username =" "; String password =" "; conn = DriverManager. getConnection (url, username, password);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} return conn; */Connection conn = null; try {JdbcConfig jdbcConfig = XmlConfigReader. getInstance (). getJdbcConfig (); Class. forName (jdbcConfig. getDriverName (); conn = DriverManager. getConnection (jdbcConfig. getUrl (), jdbcConfig. getUserName (), jdbcConfig. getPassword ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();} return conn;} public static void main (String [] args) {try {// test to obtain the information of the corresponding configuration file and generate System. out. println (DbUtil. getConnection ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}

Execution result:



Of course, it is worth mentioning that DOM4J has good support for XPath. For example, to access a node, you can directly select it using XPath:

// Element: used to describe elements in an XML document. Element driverNameElt = (Element) doc. selectObject ("/config/db-info/driver-name"); Element urlElt = (Element) doc. selectObject ("/config/db-info/url ");

The selectObject method is used here. This method returns the first matched node. If no matched node exists, null is returned. XPath is more like a selector, as long as you give conditions.


Summary
Through the above methods, we can get XML The entire document and document root node, all nodes that meet a certain condition, and a single node can be obtained. This gives the system great flexibility, dom4j makes it easier for Java to read XML files. It is faster and more efficient. When you contact the project, you can read the corresponding page information from the database address into an xml file, it is a good choice to determine the corresponding nodes to be loaded Based on the permissions and generate the corresponding permission tree ...... This reminds me of the impulse of my project!

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.