Java DOM如何检查XML中是否存在节点

Sha*_*ien 6 java xml dom

这是我的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<productlist>
<product>
<title>1</title>
<price>30</price>
</product>
<product>
<title>2</title>
<price>9</price>
</product>
<product>
<title>3</title>
</product>
</productlist>
Run Code Online (Sandbox Code Playgroud)

我需要做的是使用Java DOM API打印出包含"price"标签的XML文件中的所有内容.这样的事情

title:1
price:30 
title:2 
price:9
Run Code Online (Sandbox Code Playgroud)

在org.w3c.dom文档中,我只找到hasAttribute(String name)方法来检查这个元素是否有属性,但我在文档中找不到类似"hasTag(String name)"的方法.我找到这个网站http://www.java-forums.org/xml/62136-check-whether-xml-tag-exists-while-parsing-xml-using-dom-java.html但不幸的是我无法打开现场.希望你能帮忙.

Jon*_*eet 23

只需调用getElementsByTagName并查看返回的列表是否有任何节点(使用NodeList.getLength()).