import java.io.*; // JAXP packages import javax.xml.parsers.*; import org.w3c.dom.*; /** * DomPrint uses the Document Object Model (DOM) API to parse a given XML * document then print its element nodes. * * @author Thornton Rose * @version 1.0 */ public class DomPrint { /** * Construct an instance of this class. */ public DomPrint() { } /** * Print indentation for the given level (3 spaces per level). */ private static void printIndentation(int level) { // Print indentation. for (int i = 0; i < level; i ++) { System.out.print(" "); } } /** * Print the document starting at the given node. */ private static void print(Node node, int level) { // If not level 0, print blank line and indentation. if (level > 0) { System.out.println(""); printIndentation(level); } // Print node name. System.out.println(node.getNodeName() + ":"); // If attributes, print them. if (node.hasAttributes()) { NamedNodeMap attributes = node.getAttributes(); if (attributes.getLength() > 0) { level ++; for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); printIndentation(level); System.out.println("." + attribute.getNodeName() + "=" + attribute.getNodeValue()); } level --; } } // Get node value. String value = node.getNodeValue(); value = (value == null ? "" : value.trim()); // If node value not empty, print it. if (value.length() > 0) { printIndentation(level); System.out.println(value); } // If node has children, print them. if (node.hasChildNodes()) { level ++; NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i ++) { Node child = children.item(i); print(child, level); } } } //-------------------------------------------------------------------------- /** * Run the program. */ public static void main(String[] args) { // If not enough args, print usage. if (args.length < 1) { System.out.println("Usage: DomPrint file"); System.exit(0); } // Get file name from command-line. File docFile = new File(args[0]); try { // Get an instance of document builder factory and configure it. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); // Get a document builder from the factory. DocumentBuilder builder = factory.newDocumentBuilder(); // Parse the input file. Document doc = builder.parse(docFile); // Print the document elements. print(doc.getDocumentElement(), 0); } catch(Exception ex) { System.out.println(ex); } } }