How to Count number of Element in XML

In this article we are going to see about how to Count number of Element in XML file using DOM parser. if you wan to know more about DOM Parser read our previous articles.

CountXMLElement.java

package com.ehowtonow.xml.dom;

import java.io.File;
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 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  try {
   File xmlFile = new File("C:\\jtc\\student.xml");
   DocumentBuilderFactory builderFactory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder builder = builderFactory.newDocumentBuilder();
   Document document = builder.parse(xmlFile);
   document.getDocumentElement().normalize();
   System.out.println("Root Node :"
     + document.getDocumentElement().getNodeName());
   NodeList list = document.getElementsByTagName("student");
   System.out.println("Number of element under "
     + document.getDocumentElement().getNodeName() + " : "
     + list.getLength());
  } catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SAXException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

Student.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<college>
<student id="ECE-01">
<firstname>Sathish</firstname>
<lastname>J</lastname>
</student>
<student id="ECE-02">
<firstname>Mohan</firstname>
<lastname>P</lastname>
</student>
<student id="ECE-03">
<firstname>Saravan</firstname>
<lastname>P</lastname>
</student>
<student id="ECE-04">
<firstname>Muthu</firstname>
<lastname>S</lastname>
</student>
</college>

Output


Root Node :college

Number of element under college : 4

Output

Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. How to create XML file using DOM Parser
  2. How to Count number of Element in XML
  3. Java DOM XML Parser
  4. How to read simple XML file using DOM Parser
  5. How to Modify XML file using DOM Parser
  6. How to Read XML File using DOM parser

Be the first to comment

Leave a Reply