File.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="UTF-8"?> <company> <staff> <firstname>prasanna</firstname> <lastname>sherekar</lastname> <nickname>pashyaa</nickname> <salary>100000</salary> </staff> <staff> <firstname>james</firstname> <lastname>anderson</lastname> <nickname>lolo</nickname> <salary>200000</salary> </staff> </company> |
ReadXMLFile.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
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 ReadXMLFile { public static void main(String argv[]) { try { File fXmlFile = new File("c:\\file.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); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("First Name : " + getTagValue("firstname", eElement)); System.out.println("Last Name : " + getTagValue("lastname", eElement)); System.out.println("Nick Name : " + getTagValue("nickname", eElement)); System.out.println("Salary : " + getTagValue("salary", eElement)); } } } catch (Exception e) { e.printStackTrace(); } } private static String getTagValue(String sTag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); } } |
Output:
Root element :company
———————–
First Name : prasanna
Last Name : sherekar
Nick Name : pashyaa
Salary : 500000
First Name : james
Last Name : anderson
Nick Name : james
Salary : 200000
———————–
First Name : prasanna
Last Name : sherekar
Nick Name : pashyaa
Salary : 500000
First Name : james
Last Name : anderson
Nick Name : james
Salary : 200000