此處借鑑網絡上現有的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>