import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DOMtest { // traverse() - DOM Tree traversal using DOM API static void traverse(Document dom){ //get the root elememt Node root = (Node) dom.getDocumentElement(); // traverse from root using DFS DFStraverse(root); } // DFStraverse() : depth-first search traversal of the DOM tree static void DFStraverse(Node context) { if (context == null) return; short nodeType = context.getNodeType(); // find out the type of the node if (nodeType == Node.TEXT_NODE) // if at the leaf node output content { String content = context.getNodeValue(); // find content System.out.println(content); // print it } else if (nodeType == Node.ELEMENT_NODE) // if at element node, output tag name, traverse children { startTag(context); // start tag output Node child = context.getFirstChild(); // get first child while (child != null) { DFStraverse(child); // traverse child= child.getNextSibling(); // get next sibling } endTag(context); // end tag output } // else } // DFStraverse // startTag(): output the start tag information static void startTag(Node context) { String name = context.getNodeName(); // retrieve name of tag System.out.println(); System.out.print("Tag: "); System.out.print(name); System.out.print(" ---->"); } // endTag(): output the end tag information static void endTag(Node context) { String name = context.getNodeName(); // retrieve name of tag System.out.print("/"); System.out.println(name); } static void printContent(Node context) { String content = context.getNodeValue(); System.out.println(content); // print it } public static void main(String[] args){ // Step 1. Prepare XML document for parsing. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file Document dom = db.parse("text.xml"); // Step 2. Traverse the DOM Tree. traverse(dom); }catch(Exception e) { System.out.println(e);} } // main }