import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.*; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import java.io.IOException; import java.io.File; public class DOMxml { 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{ TreeTraverser (Node node){ switch( node.getNodeType() ){ case Node.DOCUMENT_NODE: visit((Document) node); break; case Node.ELEMENT_NODE: visit((Element) node); break; case Node.ATTRIBUTE_NODE: visit((Attr) node); break; default:; } int i; if( node.hasAttributes() ){ NamedNodeMap attributes = node.getAttributes() ; for( i=0; i < attributes.getLength(); i++ ){ new TreeTraverser ( attributes.item(i) ); } } if( node.hasChildNodes() ){ NodeList children = node.getChildNodes(); for( i=0; i < children.getLength(); i++ ){ new TreeTraverser ( children.item(i) ); } } } void visit(Document node){ System.out.println( "The root" ); } void visit(Element node){ System.out.println( "Element: " + node.getTagName() ); } void visit(Attr node){ System.out.println( "Attr: " + node.getName() ); } }