package org.madore.damlengine; import java.io.Writer; import java.io.IOException; import org.w3c.dom.*; public final class Unparser { private Node cursor; private enum Dir { PUSHING, POPPING }; private Dir dir; private Writer out; public Unparser(Document doc, Writer out) { cursor = doc; dir = Dir.PUSHING; this.out = out; } protected void skip() { Node nsib = cursor.getNextSibling(); if ( nsib == null ) { cursor = cursor.getParentNode(); dir = Dir.POPPING; } else { cursor = nsib; dir = Dir.PUSHING; } } protected void unparseOne() throws IOException { switch ( dir ) { case PUSHING: if ( cursor.getNodeType() == Node.ELEMENT_NODE ) { Element elt = (Element)cursor; out.write("<"+elt.getTagName()); if ( elt.hasAttributes() ) { NamedNodeMap attrs = elt.getAttributes(); Node n2; for ( int i=0 ; (n2=attrs.item(i)) != null ; i++ ) { Attr attr = (Attr)n2; out.write(" "+attr.getName() +"=\"(value)\""); } } if ( ! elt.hasChildNodes() ) { out.write(" />"); skip(); } else { out.write(">"); cursor = elt.getFirstChild(); } } else if ( cursor.getNodeType() == Node.DOCUMENT_NODE ) { cursor = cursor.getFirstChild(); skip(); } else if ( cursor.getNodeType() == Node.TEXT_NODE ) { out.write("(text)"); skip(); } else if ( cursor.getNodeType() == Node.COMMENT_NODE ) { out.write(""); skip(); } else if ( cursor.getNodeType() == Node.CDATA_SECTION_NODE ) { out.write(""); skip(); } else { out.write(""); skip(); } break; case POPPING: if ( cursor.getNodeType() == Node.ELEMENT_NODE ) { Element elt = (Element)cursor; out.write(""); } skip(); break; } } public void unparse() throws IOException { while ( cursor != null ) { unparseOne(); } } }