Mar 29
2009
2009
XML DOM in Java

Of late, I have been working with Java. And one of the issues that I faced was XML parsing. With so many libraries available, I decided to stick to jaxp. What follows is sample code to Tree walk over the nodes:
TreeWalk.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 | import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Tester { public static void main(String args[]) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); try { DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document doc = builder.parse(new File(args[0])); NodeList nodes1 = doc.getChildNodes(); for(int i=0; i<nodes1.getLength(); i++) { TreeWalk(nodes1.item(i), 0); } } catch(Exception e) { e.printStackTrace(); } } private static void TreeWalk(Node n, int level) { if(n.getNodeType() != Node.TEXT_NODE) { for(int i=0; i<level; i++) System.out.print(" "); System.out.print(n.getNodeName() + ":"); } else { System.out.println(n.getNodeValue().trim()); } NodeList list = n.getChildNodes(); for(int i=0; i<list.getLength(); i++) { TreeWalk(list.item(i), level+1); } } } |


