//Code to demonstrate the parsing of XML via DOM method import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.xerces.parsers.*; import java.io.*; public class PrintUsingDOM { DOMParser myDOMParser = null; String xmlFile; Document doc; Document otherdoc; public PrintUsingDOM(String fileName) { xmlFile = fileName; } public void print() { try { myDOMParser = new DOMParser(); myDOMParser.parse(xmlFile); doc = myDOMParser.getDocument(); walk(doc); } catch(Exception e) { System.out.println("Errors " + e); } } //walk the DOM tree and print as you go private void walk(Node node) { int type = node.getNodeType(); switch(type) { case Node.DOCUMENT_NODE: { System.out.println(""); break; }//end of document case Node.ELEMENT_NODE: { System.out.print('<' + node.getNodeName() ); NamedNodeMap nnm = node.getAttributes(); if(nnm != null ) { int len = nnm.getLength() ; Attr attr; for ( int i = 0; i < len; i++ ) { attr = (Attr)nnm.item(i); System.out.print(' ' + attr.getNodeName() + "=\"" + attr.getNodeValue() + '"' ); } } System.out.print('>'); break; }//end of element case Node.ENTITY_REFERENCE_NODE: { System.out.print('&' + node.getNodeName() + ';' ); break; }//end of entity case Node.CDATA_SECTION_NODE: { System.out.print( "" ); break; } case Node.TEXT_NODE: { System.out.print(node.getNodeValue()); break; } case Node.PROCESSING_INSTRUCTION_NODE: { System.out.print(" 0 ) { System.out.print(' '); System.out.print(data); } System.out.println("?>"); break; } }//end of switch //recurse for(Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { walk(child); } //without this we miss the ending tags if ( type == Node.ELEMENT_NODE ) { System.out.print(""); } }//end of walk public static void main(String args[]) { String xmlFileName=""; if(args.length == 0) { //Check to ensure user XML file name to parse System.out.println("Usage::java PrintUsingDOM path/xmlFilename"); System.exit(0); } else { xmlFileName = args[0]; } PrintUsingDOM pud = new PrintUsingDOM(xmlFileName); pud.print(); System.out.println(""); }//end of main }//end of DOM