Count XML Elements In Java Example – (DOM Parser)

Chapter: XML Last Updated: 11-06-2016 18:42:25 UTC

Program:

            /* ............... START ............... */
                
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class JavaCountXMLElements {
	public static void main(String argv[]) {

		try {
			String filepath = "c:\\file.xml";
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(filepath);

			NodeList list = doc.getElementsByTagName("staff");

			System.out.println("Total of elements : " + list.getLength());

		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (SAXException sae) {
			sae.printStackTrace();
		}
	}
}
                /* ............... END ............... */
        

Output

Total of elements : 3

Notes:

  • DOM Parser to count the total number of elements in a XML file.
  • NodeList.getLength() to get the total number of available elements.

Tags

Count XML Elements, Java

Similar Programs Chapter Last Updated
XML File Creation In Java Example – (DOM Parser) XML 06-07-2016
Read XML File In Java Example – (DOM Parser) XML 15-07-2016
Modify XML File In Java Example – (DOM Parser) XML 15-07-2016

1