/** * Written by SaEeD * Description : Example of using XML file in Java * ######## PLEASE DOWNLOAD THIS XML FILE TO TEST THIS APPLICATION ########## */ import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; 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 TestXMLFile { public TestXMLFile() { } public static void main(String[] args) throws Exception { if(args.length != 1) { System.err.println("Usage: java TestXMLFile <XML file>"); System.exit(1); } String filename = args[0]; File myFile = new File(filename); System.out.println("[+]XML Filename: " + filename); System.out.print("Please enter the tag name: "); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String input = stdin.readLine(); System.out.println("[+]Tag name: " + input ); /////////////////////////////////////////////////////////////////// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(myFile); ///////////////////// Normalize /////////////////////////// doc.getDocumentElement().normalize(); System.out.println("[+]Root Element: " + doc.getDocumentElement().getNodeName()); ///////////////////////Getting the Nodes//////////////////////// NodeList listOfBooks = doc.getElementsByTagName(input); int TotalBooks = listOfBooks.getLength(); System.out.println("[+]Total number: " + TotalBooks); for(int i=0; i < TotalBooks; i ++) { Node node = listOfBooks.item(i); System.out.println("[+]Node Type: " + node.getNodeType()); Element element = (Element)node; //--- in God Attribute NodeList name = element.getElementsByTagName("name"); Element el = (Element)name.item(0); System.out.println("[+]Name: " + el.getFirstChild().getNodeValue()); } } }