How to read xml file in java?

How to Read Xml File In java:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXml {

public static void main(String argv[]) {

try {

File XmlFile = new File("E:/StudentFile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(XmlFile);
doc.getDocumentElement().normalize();
System.out.println("RootElement :"+doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("Student");

System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("\nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element sElement = (Element) nNode;

System.out.println("Student id : " + sElement.getAttribute("stundentId"));
System.out.println("Student Name : " + sElement.getElementsByTagName("studentName").item(0).getTextContent());
System.out.println("Address Name : " + sElement.getElementsByTagName("address").item(0).getTextContent());
System.out.println("Email : " + sElement.getElementsByTagName("email").item(0).getTextContent());
System.out.println("Phone Number : " + sElement.getElementsByTagName("phoneNumber").item(0).getTextContent());

}
}
} catch (Exception e) {
e.printStackTrace();
}
}


}
Output of the above program is:
Root element :college
----------------------------

Current Element :Student
Student id : 1
Student Name : sunny
Address Name : hyderabad
Email : sunny@gmail.com
Phone Number : 9080706050

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.