Parse XML file and print out corresponding NodeList in Java

ziex

New Member
I have an XML file I would like to search through based on console input in Java. If the input finds a match within a certain tag, it should print out the corresponding NodeList. I have searched and not been able to find what I was looking for.XML file:\[code\]<DATABASE> <USER> <ID>1</ID> <FIRSTNAME>User</FIRSTNAME> <LASTNAME>Name</LASTNAME> <USERNAME>username</USERNAME> <PASSWORD>password</PASSWORD> </USER> <USER> <ID>2</ID> <FIRSTNAME>John</FIRSTNAME> <LASTNAME>Doe</LASTNAME> <USERNAME>john.doe</USERNAME> <PASSWORD>password</PASSWORD> </USER></DATABASE>\[/code\]Java:\[code\]private void viewByUsername() throws ParserConfigurationException, IOException, SAXException, TransformerConfigurationException{ Scanner scan = new Scanner(System.in); System.out.println("Enter username to find: "); String input = scan.nextLine(); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse("XMLData/UserDatabase.xml"); doc.getDocumentElement().normalize(); NodeList users = doc.getElementsByTagName("USER"); for (int temp = 0; temp < users.getLength(); temp++){ Node nNode = users.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; } }\[/code\]
 
Back
Top