JAVA XML

JavaXml Projects

JavaXml Project 1

JavaXml Examples

JavaXml EXAMPLE

adplus-dvertising
Count the Elements in a XML File
Previous Home Next

In this we learn that how we will count the element in XML file using DOM APIs defined in the org.apache.xerces.parsers.DOMParser package. Your classpath must contain xercesImpl.jar and xml-apis.jar files to run this program. we can download it from Xerces

Here is the XML File: Stusent_Detail.xml

<?xml version = "1.0" ?>
<Student_Detail>
<Student>
<stu_Id> s-001 </stu_Id>
<stu_Name> samir </stu_Name>
<stu_E-mail> sam1@yahoo.com </stu_E-mail>
</Student>
<Student>
<stu_Id> s-002 </stu_Id>
<stu_Name> Ajit </stu_Name>
<stu_E-mail> Ajit2@gmail.com </stu_E-mail>
</Student>
<Student>
<stu_Id> s-003 </stu_Id>
<stu_Name> Deepti </stu_Name>
<stu_E-mail> Deep3@yahoo.com </stu_E-mail>
</Student>
</Student_Detail>

Here is the Java File: CountNodes.java

package r4r;
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;
public class totalnode {
public static void main(String[] args) {
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Enter the file name: ");
String str = br.readLine();
File file = new File(str);
if (file.exists()){
DOMParser pars = new DOMParser();
pars.parser(str);
Document docu = pars.getDocument();
System.out.print("Enter element to count: ");
String ele = br.readLine();
NodeList list1 = docu.getElementsByTagName(ele);
System.out.println("Number of nodes: " + list1.getLength());
}
else{
System.out.println("File not found!");
}
}
catch (Exception e){
e.getMessage();
}
}
}
package org.apache.xerces.parsers;
import org.w3c.dom.Document;
public class DOMParser {
public void parser(String str) {
// TODO Auto-generated method stub
}
public Document getDocument() {
// TODO Auto-generated method stub
return null;
}
}
Previous Home Next