这是我的XML
<action>
<name>EDIT</name>
<type>123</type>
<services>
<service>
this is child node
</service>
<services>
</action>
上面的XML具有根节点和childNode,,,所以我们想找到具有任何childNodes或text的childNodes,因此要找到它,我们在下面的Java代码中进行了解析
File fXmlFile = new File("/opt/staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList1 = doc.getElementsByTagName("action");
// for loop
for (int i = 0; i < nList1.getLength(); i++) {
Node node = nList1.item(i);
NodeList childNodeList = node.getChildNodes();
for (int childCount = 0; childCount < childNodeList.getLength(); childCount++) {
Node gChild = childNodeList.item(childCount);
if (Node.ELEMENT_NODE != childNodeList.getNodeType()) {
continue;
} // end of if
if(gChild.hasChildNodes()){
System.out.print("having child node ");
}else{
System.out.print("not having child node ");
}
}//end Of For
}//end Of For
因此,当我们执行上述代码时,它应该像这样打印出来
not having child node
not having child node
having child node
因为<name>
和<type>
节点不具有childNode,而<services>
节点具有childNode,但它正在打印这样的输出
having child node
having child node
having child node
当我在Google上搜索此问题时,我获得了以下链接,我已经尝试过,但是我的问题没有解决 How to know if a tag contains a value or another tag? 谁能帮我