首页 > 代码库 > 使用Dom4j解析XML文件
使用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()); } }
使用Dom4j解析XML文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。