此处借鉴网络上现有的xml 创建book.xml,下面测试是否存在界面city
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="001">
<title>Harry Potter</title>
<author>J K. Rowling</author>
</book>
<book id="002">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<city>test</city>
</book>
</books>
另一种通过elementText获取节点值:
if (child.elementText("city") != null) { //无此节点时,获取的值为null System.out.println("city" +child.elementText("city")); }
两种方式执行效果是一样的,注意判断获取的结果,无论定义何种变量,返回的是null
执行结果如下
需要引入jar。版本根据需要填写
<dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> </dependency>