Total Pageviews

Wednesday 10 September 2014

How to read xml file using java.

Example XML fiile shown bellow.

<class> //It is root element

<student rollno='001'>
<firstname>Parimi</firstname>
<lastname>satish</lastname>
<nickname>pandu</nickname>
</student>

<student rollno='002'>
<firstname>maha</firstname>
<lastname>madi</lastname>
<nickname>dinga</nickname>
</student>

</class>



----------------------------------------------------------------------------------------------------------------------
use the bellow code, and change the file path..

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadCustomXMLFile
{

public static void main(String [] args)
{
try
{
File fXmlFile = new File("E:\\tutorials\\Selenium Videos\\xml filehandling\\testdata.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

//To get Root element i.e class  ---- in testda.xml file
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());


// get no of sub - nodes i.e "student" nodes in the xml file
NodeList nList = doc.getElementsByTagName("student");
System.out.println(nList.getLength());


//get all the attribute values in the both sub nodes...

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

//to Get all sub-nodes names use bello code....
Node nNode = nList.item(temp);
System.out.println("Sub Node Name is :  "+nNode.getNodeName());


//

if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;


//to get roll no of the  student
System.out.println("Student ID is :"+eElement.getAttribute("rollno"));


//to get firstname of the student
System.out.println("First Name is: "+eElement.getElementsByTagName("firstname").item(0).getTextContent());

//To get Last name of the Student
System.out.println("Last Name is :"+eElement.getElementsByTagName("lastname").item(0).getTextContent());

//To get Nick Name of the Student is
System.out.println("Nick Name is :"+eElement.getElementsByTagName("nickname").item(0).getTextContent());

}

}

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

}
}

No comments:

Post a Comment