Say I have the following XML file:
<?xml version="1.0" encoding="utf-8"?> <venues> <group type="Nearby"> <venue> <id>222307</id> <name>Union Chapel</name> <primarycategory> <id>78967</id> <fullpathname>Arts & Entertainment:Music Venue</fullpathname> <nodename>Music Venue</nodename> <iconurl>http://foursquare.com/img/categories/arts_entertainment/musicvenue.png</iconurl> </primarycategory> <address>Compton Ave</address> <city>Islington</city> <state>Greater London</state> <zip>N1 2XD</zip> <verified>false</verified> <geolat>51.5439732</geolat> <geolong>-0.1020908</geolong> <stats> <herenow>0</herenow> </stats> <phone>02073594019</phone> <distance>33</distance> </venue>
.............
and my code is the following:
XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//venue/*"); Object result = expr.evaluate(document, XPathConstants.NODESET); NodeList nodes = (NodeList) result; //System.out.println(nodes.getLength()); Venue ven = new Venue(); for (int i = 0; i < nodes.getLength(); i++) { String nodeName = nodes.item(i).getNodeName(); String nodeValue = nodes.item(i).getNodeValue(); if (nodeName.equals("id")){ ven = new Venue(); if (nodeValue != null) ven.id = Integer.parseInt(nodeValue); System.out.println(ven.id); } if (nodeName.equals("name")){ ven.name = nodeValue; System.out.println(ven.name); } if (nodeName.equals("address")){ ven.address = nodeValue; System.out.println(ven.address); }
How can I do all of this in one for loop for efficiency? Otherwise for every attribute in the xml that I want to extract I need to create a for loop for each one of them