1、导包
2、创建sys-config.xml
<?xml version="1.0" encoding="UTF-8"?> <config> <database-info> <driver-name>com.mysql.jdbc.Driver</driver-name> <url>jdbc:mysql://localhost:3306/sys?serverTimezone=GMT%2B8</url> <user>root</user> <password>123</password> </database-info> </config>
3、dom4j+Xpath的简单路径表达式获取节点元素内容和属性值
package com.zda.xml; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class SysConfigParser { /** * @param args */ public static void main(String[] args) { try { //创建解析器 SAXReader reader = new SAXReader(); //通过解析器的read方法将配置文件读取到内存中,生成一个Dcoumente【org.dom4j】对象树 Document document = reader.read("conf/sys-config.xml"); //driver-name节点元素的路径:config -> database-info -> driver-name // driver-name节点元素的xpath路径:/config/database-info/driver-name Element driverNameElt = (Element) document.selectSingleNode("/config/database-info/driver-name"); //获取driverNameElt节点元素对象的文本内容 String driverName = driverNameElt.getStringValue(); System.out.println(driverName); //url节点元素的路径: config -> database-info -> url //url节点元素的xpath路径: /config/database-info/url //url节点元素的xpath路径: config//url //url节点元素的xpath路径: //url Element urlElt = (Element) document.selectSingleNode("/config//url"); String url = urlElt.getStringValue(); System.out.println(url); //user节点元素的路径:config -> database-info -> user //user节点元素的xpath路径:/config/database-info/user //user节点元素的xpath路径:config//user //user节点元素的xpath路径://user Element userElt = (Element) document.selectObject("//user"); String user = userElt.getText(); System.out.println(user); //获取userElt节点元素对象的name属性对象 Attribute portAttr = userElt.attribute("name"); //获取portAttr节点name属性对象的值,方法1 String port = portAttr.getStringValue(); System.out.println(port); //获取portAttr节点name属性对象的值,方法2 String portValue = userElt.attributeValue("name"); System.out.println(portValue); Element passwordElt = (Element) document.selectSingleNode("//password"); String password = passwordElt.getTextTrim(); System.out.println(password); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
输出结果
(三)dom4j+Xpath的简单路径表达式获取节点元素内容和属性值
原文:https://www.cnblogs.com/zhaideang/p/12310445.html