/* * (C) Copyright IBM Corp. 2004. All rights reserved. * * US Government Users Restricted Rights Use, duplication or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. * * The program is provided "as is" without any warranty express or * implied, including the warranty of non-infringement and the implied * warranties of merchantibility and fitness for a particular purpose. * IBM will not be liable for any damages suffered by you as a result * of using the Program. In no event will IBM be liable for any * special, indirect or consequential damages or lost profits even if * IBM has been advised of the possibility of their occurrence. IBM * will not be liable for any third party claims against you. */ import java.util.Stack; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * A SAX application that builds a DOM tree from the SAX events, * then traverses the tree backwards. */ public class SaxToDom extends DefaultHandler { DocumentBuilderFactory dbf = null; DocumentBuilder docBuilder = null; Document root = null; boolean firstElementNotFoundYet = true; Stack elementStack = null; /** Prints the specified node, recursively. */ public void printDOMTree(Node node) { int type = node.getNodeType(); switch (type) { // print the document element case Node.DOCUMENT_NODE: { System.out.println(""); printDOMTree(((Document)node).getDocumentElement()); break; } // print element with attributes case Node.ELEMENT_NODE: { System.out.print("<"); System.out.print(node.getNodeName()); if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) printDOMTree(attrs.item(i)); } System.out.print(">"); if (node.hasChildNodes()) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) printDOMTree(children.item(i)); } break; } // Print attribute nodes case Node.ATTRIBUTE_NODE: { System.out.print(" " + node.getNodeName() + "=\""); if (node.hasChildNodes()) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) printDOMTree(children.item(i)); } System.out.print("\""); break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { System.out.print("&"); System.out.print(node.getNodeName()); System.out.print(";"); break; } // print cdata sections case Node.CDATA_SECTION_NODE: { System.out.print(""); break; } // print text case Node.TEXT_NODE: { System.out.print(node.getNodeValue()); break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { System.out.print(""); break; } } if (type == Node.ELEMENT_NODE) { System.out.print("'); } } // printDOMTree(Node) public void parseAndPrint(String uri) { try { dbf = DocumentBuilderFactory.newInstance(); docBuilder = dbf.newDocumentBuilder(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); sp.parse(uri, this); if (root != null) printDOMTree(root); } catch (ParserConfigurationException pce) { System.err.println("Parser configuration error : " + pce); } catch (Exception e) { System.err.println(e); } } /** Start document. */ public void startDocument() { // If we knew the name of the root element, we could create // the Document object here. We don't know the name of the // root, so we'll create it in startElement(), using a flag // to see if this is our first (aka root) element. } /** Start element. */ public void startElement(String namespaceURI, String localName, String rawName, Attributes attrs) { if (firstElementNotFoundYet) { root = docBuilder.getDOMImplementation(). createDocument(namespaceURI, rawName, null); Element docElement = root.getDocumentElement(); if (attrs != null) { int len = attrs.getLength(); for (int i = 0; i < len; i++) docElement.setAttribute(attrs.getQName(i), attrs.getValue(i)); } elementStack = new Stack(); elementStack.push(docElement); firstElementNotFoundYet = false; } else { Element currentElement = root.createElement(rawName); if (attrs != null) { int len = attrs.getLength(); for (int i = 0; i < len; i++) currentElement.setAttribute(attrs.getQName(i), attrs.getValue(i)); } elementStack.push(currentElement); } } // startElement /** Ignorable whitespace. */ public void ignorableWhitespace(char ch[], int start, int length) { characters(ch, start, length); } /** Characters. */ public void characters(char ch[], int start, int length) { ((Element) elementStack.peek()). appendChild(root.createTextNode(new String(ch, start, length))); } // characters(char[],int,int); /** End element. */ public void endElement(String namespaceURI, String localName, String rawName) { if (elementStack.size() > 1) { Element currentElement = (Element) elementStack.pop(); ((Element) elementStack.peek()).appendChild(currentElement); } } // endElement(String) /** End document. */ public void endDocument() { // Do nothing... } // endDocument() /** Processing instruction. */ public void processingInstruction(String target, String data) { ((Element) elementStack.peek()). appendChild(root.createProcessingInstruction(target, data)); } // processingInstruction(String,String) // // ErrorHandler methods // /** Warning. */ public void warning(SAXParseException ex) { System.err.println("[Warning] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Error. */ public void error(SAXParseException ex) { System.err.println("[Error] "+ getLocationString(ex)+": "+ ex.getMessage()); } /** Fatal error. */ public void fatalError(SAXParseException ex) throws SAXException { System.err.println("[Fatal Error] "+ getLocationString(ex)+": "+ ex.getMessage()); throw ex; } /** Returns a string of the location. */ private String getLocationString(SAXParseException ex) { StringBuffer str = new StringBuffer(); String systemId = ex.getSystemId(); if (systemId != null) { int index = systemId.lastIndexOf('/'); if (index != -1) systemId = systemId.substring(index + 1); str.append(systemId); } str.append(':'); str.append(ex.getLineNumber()); str.append(':'); str.append(ex.getColumnNumber()); return str.toString(); } // getLocationString(SAXParseException):String /** Main program entry point. */ public static void main(String argv[]) { if (argv.length == 0 || (argv.length == 1 && argv[0].equals("-help"))) { System.out.println("\nUsage: java SaxToDom uri"); System.out.println(" where uri is the URI of your XML document."); System.out.println(" Sample: java SaxToDom sonnet.xml"); System.out.println("\nEchoes SAX events back to the console."); System.exit(1); } SaxToDom s2d = new SaxToDom(); s2d.parseAndPrint(argv[0]); } // main(String[]) }