Parsing XML files and parsing XML files
1. The reason for applying the configuration file is that we often use the configuration file in the program. We want to configure the parameters in the configuration file to facilitate database replacement when using the abstract factory, in addition, to read some variable information, you also need to put it in the configuration file, which is convenient, flexible, and so on.
2. Using the configuration file preparation work needs to reference two jar packages: dom4j-1.6.1 and jaxen-1.1-beta-6.jar reasons: 1). dom4j is a Java xml api, similar to jdom, used to read and write XML files
2 ). when using dom4j to parse XML, it is a good way to get the data of a node quickly, using XPath is also recommended in the dom4j quick manual, XPath comes from the package jaxen-1.1-beta-6.jar.
3. Specific operations on XML files
1) the XML file is as follows (File Name: sys-conf.xm ):
<? Xml version = "1.0" encoding = "UTF-8"?>
<Config> <db-info> <driver-name> oracle. jdbc. driver. oracle driver </driver-name> <url> jdbc: oracle: thin: @ 127.0.0.1: 1521: ORCL </url> <user-name> *** </user-name> <password> *** </password> </db-info> </config>
2) read the XML file as follows:
// Define the read XML Document Object
SAXReader reader = new SAXReader (); // get the xml Path InputStream in = Thread. currentThread (). getContextClassLoader (). getResourceAsStream ("sys-conf.xml"); try {// method for getting the value in the xml file ------- start Document doc = reader. read (in); Element driverNameElt = (Element) doc. selectObject ("/config/db-info/driver-name"); String driverName = driverNameElt. getStringValue (); System. out. println (driverName); // method for getting the value in the xml file ------- end} catch (incluentexception e ){
// TODO Auto-generated catch block e. printStackTrace ();}