JAVA XML

JavaXml Projects

JavaXml Project 1

JavaXml Examples

JavaXml EXAMPLE

Fetch all XML Elements
Previous Home Next

In this program, we will be study how to retrieve every elements of the XML file with help of the DOM Application programming Interface. The API provides some methods and constructors which is help to parse the XML file and retrieve all elements.

Here is the XML File: Student_Detail.xml

<?xml version = "1.0" ?>
<Student_Detail>
<Student>
<stu_Id> s-001 </stu_Id>
<stu_Name> samir </stu_Name>
<stu_E-mail> sam1@gmail.com </stu_E-mail>
</Student>
<Student>
<stu_Id> s-002 </stu_Id>
<stu_Name> Ajit </stu_Name>
<stu_E-mail> Ajit2@yahoo.com </stu_E-mail>
</Student>
<Student>
<stu_Id> E-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: Studentrecord.java

package r4r;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class fetchrecord {
public static void main(String[] arg){
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Enter the XML File name: ");
String str = br.readLine();
File file = new File(str);
if(file.exists()){
DocumentBuilderFactory fact =
DocumentBuilderFactory.newInstance();
DocumentBuilder build = fact.newDocumentBuilder();
Document docu = build.parse(str);
NodeList list1 = docu.getElementsByTagName("*");
System.out.println("XML Elements: ");
for (int i=0; i<list1.getLength(); i++) {
Element ele = (Element)list1.item(i);
System.out.println(ele.getNodeName());
}
}
else{
System.out.print("File not found!");
}
}
catch (Exception e) {
System.exit(1);
}
}
}
Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: