728x90 AdSpace

Spring
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.
CountXMLElement.java
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
.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>

Now run the program see the following output in console.

Root Node :college

Number of element under college : 4
  • Blogger Comments
  • Disqus Comments

0 comments:

Post a Comment

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