728x90 AdSpace

Sunday, 10 November 2013

Count XML Element using DOM parser

In this tutorials we going to see how to count the element in XML document using DOM parser .
1. Create Project Called JavaXML.
2. Create package called com.javatutorialscorner.xml.dom under JavaXML.
3. Create Java class called CountXMLElement.java under com.javatutorialscorner.xml.dom package.
package com.javatutorialscorner.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
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
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
} catch (SAXException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block




<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<student id="ECE-01">
<student id="ECE-02">
<student id="ECE-03">
<student id="ECE-04">

Now run the program see the following output in console.

Root Node :college

Number of element under college : 4
Annamalai Thangaraj

Annamalai is a Sr.Software Engineer with 3+ years experience in Java, Spring, Struts, Hibernate, IDM/IAM, and Enterprise Web Application Development.

Website: Java Tutorials Corner

  • Blogger Comments
  • Facebook Comments
  • Disqus Comments


Post a Comment

Item Reviewed: Count XML Element using DOM parser Rating: 5 Reviewed By: Annamalai Thangaraj