How to count XML Elements in Java – (DOM Parser)

In this example, we show you how to use DOM Parser to count the total number of elements in a XML file. First, search the element name, and then you can use NodeList.getLength() to get the total number of available elements.


	NodeList list = doc.getElementsByTagName("staff");
	System.out.println("Total of elements : " + list.getLength());

File : file.xml


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
	<staff id="1">
		<firstname>yong</firstname>
		<lastname>mook kim</lastname>
		<nickname>mkyong</nickname>
		<salary>2000000</salary>
		<age>29</age>
	</staff>
	<staff id="2">
		<firstname>low</firstname>
		<lastname>yin fong</lastname>
		<nickname>fong fong</nickname>
		<salary>1000000</salary>
	</staff>
	<staff id="3">
		<firstname>Ali</firstname>
		<lastname>Baba</lastname>
		<nickname>Alibaba</nickname>
		<salary>199000</salary>
		<age>40</age>
	</staff>
</company>

File : CountXMLElement.java – Search total number of available “staff” elements.


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 CountXMLElement {

  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();
	}
  }
}

Output


Total of elements : 3

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
11 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
9 Comment authors
sadeeshalJayAmirKossi Fiadjigbesemaphore Recent comment authors
newest oldest most voted
trackback
Java XML Tutorial

[…] delete a element.Create a new XML file Create a XML file with new document, element and attribute.Count XML Elements Search and count total number of elements in a XML file.SAX XML ParserSAX parser is work […]

trackback
(Java) Membaca File XML – (DOM Parse) « Mr.Root

[…] http://www.mkyong.com/java/how-to-count-xml-elements-in-java-dom-parser/ Share this:TwitterFacebookLike this:LikeBe the first to like this. Permalink […]

Anonymous Please.
Guest
Anonymous Please.

What if we do not know the element name , what if we the XML has uniquely named elements.

Quân Chùa
Guest
Quân Chùa

doc.getChildNodes().getLength() maybe true

trackback
How to count the depth of xml document (DOM example)

[…] How To Count XML Elements In Java – (DOM Parser) […]

Khemlal Chhetri
Guest
Khemlal Chhetri

Since the above code is to read xml file and search for total staff elements, i am in need to create xml of n number of staff elements using a for loop because all my values are coming from database. So my file should look exactly like the file.xml you have with multiple staff elements. How do i do that for dynamic values? Please share me the code…

James
Guest
James
semaphore
Guest
semaphore

thank you very much

I would ask you : how to extract the content of xml and put in doc.txt

thank you

Kossi Fiadjigbe
Guest
Kossi Fiadjigbe

You are the best Mkyong

Amir
Guest
Amir

how to implement a simple parser that does well-formedness checking on XML, such as
the following:

x
y
z

without using a parser like Xerces.

Jay
Guest
Jay

Thsnk u very much tht helped alot..

sadeeshal
Guest
sadeeshal

I have a Object called Student like this class Student{ int a; String name; List childStudents; } and my xml looks like this 1 ABC 2 XYZ 3 PQR Now what I want is read the XML and fill the values to Student Objects, in first Student Object as per XML only have values “a” and “name” only it doesn’t have List of child students but in second element in xml has “a,name” and child student as well which is same as parent object student “a,name, and list of students”, so what I want is as per xml values fill… Read more »