使用Dom4j解析XML文件
项目目录树:
jdbcConfig.xml文件
<?xml version="1.0" encoding="UTF-8"?> <config> <jdbc> <username>sushe</username> <password>sushe</password> <url>jdbc:mysql://172.16.100.10:3306/sushe</url> <driverName>com.mysql.jdbc.Driver</driverName> </jdbc> </config>
JdbcBean.java
package com.dlab.bean; public class JdbcBean { private String userName; private String password; private String url; private String driverName; 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; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this.driverName = driverName; } }
JdbcConfigXML.java
package com.dlab.util; import java.io.InputStream; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.dlab.bean.JdbcBean; /** * 读取xml文件工具类 * @author djoker * */ public class JdbcConfigXML { private JdbcBean jdbcBean; public JdbcConfigXML(){ jdbcBean = new JdbcBean(); SAXReader reader = new SAXReader(); InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbcConfig.xml"); try { //读取配置文件 Document doc = reader.read(in); //取得元素 Element usernameElt = (Element)doc.selectObject("/config/jdbc/username"); Element passwordElt = (Element)doc.selectObject("/config/jdbc/password"); Element urlElt = (Element)doc.selectObject("/config/jdbc/url"); Element driverNameElt = (Element)doc.selectObject("/config/jdbc/driverName"); //赋值到jdbcBean对象中 jdbcBean.setUserName(usernameElt.getStringValue()); jdbcBean.setPassword(passwordElt.getStringValue()); jdbcBean.setUrl(urlElt.getStringValue()); jdbcBean.setDriverName(driverNameElt.getStringValue()); } catch (DocumentException e) { e.printStackTrace(); } } //返回配置对象jdbcBean public JdbcBean getJdbcBean(){ return jdbcBean; } //主方法测试 public static void main(String[] args){ JdbcConfigXML a = new JdbcConfigXML(); JdbcBean j = a.getJdbcBean(); System.out.println(j.getUserName()); System.out.println(j.getPassword()); System.out.println(j.getUrl()); System.out.println(j.getDriverName()); } }