database.xml
<?xml version="1.0" encoding="utf-8"?> <config> <database-info> <driver-name>com.mysql.jdbc.Driver</driver-name> <url>jdbc:mysql://192.168.1.151:3306/db_test</url> <user>root</user> <password>123</password> </database-info> </config>
package edu.aeon.xml; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * [说明]:dom4j+xpath解析xml文档 * 需要jar包: * dom4j-1.6.1.jar * jaxen-1.1-beta-7.jar * @author aeon(qq:1584875179) * */ public class Dom4jXpath { public static void main(String[] args) { try { SAXReader saxReader=new SAXReader(); Document document=saxReader.read("config/database.xml"); //driver-name节点元素的路径:config->database-info->driver-name /** * 对应xpath路径写法为: * /config/database-info/driver-name * config//driver-name * //driver-name */ Element driverNameElement=(Element) document.selectSingleNode("/config/database-info/driver-name");//选上面三种里面的任何一种xpath路径即可 //获取driverNameElement节点元素对象的内容 String driverNameElementContext=driverNameElement.getStringValue(); System.out.println(driverNameElementContext); } catch (DocumentException e) { e.printStackTrace(); } } }
结果截图: