/* * (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 javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; 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.AttributesImpl; import org.xml.sax.helpers.DefaultHandler; public class DomToSax extends DefaultHandler { DocumentBuilderFactory dbf = null; DocumentBuilder db = null; public void parseAndPrint(String uri) throws SAXException { Document doc = null; try { dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); doc = db.parse(uri); if (doc != null) generateSAXEvents(doc, this); } catch (Exception e) { System.err.println("Sorry, an error occurred: " + e); } } /** Generates SAX events from the DOM tree. */ public void generateSAXEvents(Node node, DefaultHandler dh) throws SAXException { int type = node.getNodeType(); switch (type) { // The document node corresponds to the startDocument() event case Node.DOCUMENT_NODE: { dh.startDocument(); generateSAXEvents(((Document)node).getDocumentElement(), dh); dh.endDocument(); break; } // print element with attributes case Node.ELEMENT_NODE: { AttributesImpl saxAttrs = new AttributesImpl(); if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) saxAttrs.addAttribute(null, null, attrs.item(i).getNodeName(), null, attrs.item(i).getNodeValue()); } dh.startElement(null, null, node.getNodeName(), saxAttrs); if (node.hasChildNodes()) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) generateSAXEvents(children.item(i), dh); } dh.endElement(null, null, node.getNodeName()); break; } // print text case Node.TEXT_NODE: { char[] chars = node.getNodeValue().toCharArray(); dh.characters(chars, 0, chars.length); break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { dh.processingInstruction(node.getNodeName(), node.getNodeValue()); break; } } } // generateSAXEvents(Node, ContentHandler) /** Start document. */ public void startDocument() { System.out.println(""); } // startDocument() /** Start element. */ public void startElement(String namespaceURI, String localName, String rawName, Attributes attrs) { System.out.print("<"); System.out.print(rawName); if (attrs != null) { int len = attrs.getLength(); for (int i = 0; i < len; i++) { System.out.print(" "); System.out.print(attrs.getQName(i)); System.out.print("=\""); System.out.print(attrs.getValue(i)); System.out.print("\""); } } System.out.print(">"); } // startElement(String,AttributeList) /** Characters. */ public void characters(char ch[], int start, int length) { System.out.print(new String(ch, start, length)); } // characters(char[],int,int); /** Ignorable whitespace. */ public void ignorableWhitespace(char ch[], int start, int length) { characters(ch, start, length); } // ignorableWhitespace(char[],int,int); /** End element. */ public void endElement(String namespaceURI, String localName, String rawName) { System.out.print(""); } // endElement(String) /** End document. */ public void endDocument() { // No need to do anything. } // endDocument() /** Processing instruction. */ public void processingInstruction(String target, String data) { System.out.print(" 0) { System.out.print(' '); System.out.print(data); } System.out.print("?>"); } // 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 DomToSax uri"); System.out.println(" where uri is the URI of your XML document."); System.out.println(" Sample: java DomToSax sonnet.xml"); System.out.println("\nEchoes SAX events back to the console."); System.exit(1); } DomToSax d2s = new DomToSax(); try { d2s.parseAndPrint(argv[0]); } catch (SAXException se) { } } // main(String[]) }