Reading Data From XML file in JAVA
Reading of xml data from file you need to parse xml it means you need to go through xml
Program:
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 xmlReader {
public static void main(String argv[]) {
try {
File fXmlFile = new File("person.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Staff");
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 eElement = (Element)
System.out.println("First Name : " + eElement.getElementsByTagName("FirstName").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("Salary").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
To Run Program:
(compilation) $ javac xmlReader.java
(run) $ java xmlReader
No comments:
Post a Comment