import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.NamedNodeMap; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import java.io.IOException; import java.io.File; public class DOMNodes { public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse (new File(args[0]).toURL().toString()); new TreeTraverser (doc); } } class TreeTraverser{ static String indent=""; TreeTraverser (Node node){ String s = node.getNodeValue(); System.out.println( indent + node.getNodeName() + " <<" + (s==null? "null" : s.trim()) + ">>"); int i; indent += " "; if( node.hasAttributes() ){ System.out.println( indent + "ATTRIBUTES:" ); NamedNodeMap attributes = node.getAttributes() ; for( i=0; i < attributes.getLength(); i++ ){ new TreeTraverser ( attributes.item(i) ); } } if( node.hasChildNodes() ){ System.out.println( indent + "CHILDREN:" ); NodeList children = node.getChildNodes(); for( i=0; i < children.getLength(); i++ ){ new TreeTraverser ( children.item(i) ); } } indent = indent.substring(2); } }