Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java DOM How to check if node exists in XML

Tags:

java

dom

xml

Here is my xml file

<?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>

What I need to do is use Java DOM API to print out all the contents from XML file which contain "price" tag. Such things like this

title:1
price:30 
title:2 
price:9

In the org.w3c.dom documentation I only find hasAttribute(String name) method to check if this element have attribute but I can not find method like "hasTag(String name)" in documentation. I find this website http://www.java-forums.org/xml/62136-check-whether-xml-tag-exists-while-parsing-xml-using-dom-java.html but unfortunately I can not open the site. Hope you can help.

like image 713
Shawn Lien Avatar asked Apr 04 '13 16:04

Shawn Lien


People also ask

How do I check if a node exists in XML?

You can iterate through each and every node and see if a node exists. doc. Load(xmlPath); XmlNodeList node = doc. SelectNodes("//Nodes/Node"); foreach (XmlNode chNode in node) { try{ if (chNode["innerNode"]==null) return true; //node exists //if ...

How do you check if an element exists in the XML using XPath?

Use the fn:nilled XPath function to test whether the value of an input element has the xsi:nil attribute set. Use the fn:exists XPath function to test whether the value of an input element is present. Note: An XML element that has the xsi:nil attribute set is considered to be present.

What is node in XML DOM?

According to the XML DOM, everything in an XML document is a node: The entire document is a document node. Every XML element is an element node. The text in the XML elements are text nodes.


1 Answers

Just call getElementsByTagName and see if the returned list has any nodes (using NodeList.getLength()).

like image 81
Jon Skeet Avatar answered Dec 28 '22 12:12

Jon Skeet