Here is the input xml file that we need to query −
<?xml version = "1.0"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferarri 101</carname> <carname type = "sports car">Ferarri 201</carname> <carname type = "sports car">Ferarri 301</carname> </supercars> <supercars company = "Lamborgini"> <carname>Lamborgini 001</carname> <carname>Lamborgini 002</carname> <carname>Lamborgini 003</carname> </supercars> <luxurycars company = "Benteley"> <carname>Benteley 1</carname> <carname>Benteley 2</carname> <carname>Benteley 3</carname> </luxurycars> </cars>
package com.howcodex.xml; 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 QueryXmlFileDemo { public static void main(String argv[]) { try { File inputFile = new File("input.txt"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); System.out.print("Root element: "); System.out.println(doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("supercars"); System.out.println("----------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :"); System.out.print(nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.print("company : "); System.out.println(eElement.getAttribute("company")); NodeList carNameList = eElement.getElementsByTagName("carname"); for (int count = 0; count < carNameList.getLength(); count++) { Node node1 = carNameList.item(count); if (node1.getNodeType() == node1.ELEMENT_NODE) { Element car = (Element) node1; System.out.print("car name : "); System.out.println(car.getTextContent()); System.out.print("car type : "); System.out.println(car.getAttribute("type")); } } } } } catch (Exception e) { e.printStackTrace(); } } }
This would produce the following result −
Root element: cars ---------------------------- Current Element : supercarscompany : Ferrari car name : Ferarri 101 car type : formula one car name : Ferarri 201 car type : sports car car name : Ferarri 301 car type : sports car Current Element : supercarscompany : Lamborgini car name : Lamborgini 001 car type : car name : Lamborgini 002 car type : car name : Lamborgini 003 car type :