From 00dc8d9bbb54cf9a0cc47e6326a8444df92a14f1 Mon Sep 17 00:00:00 2001 From: "David A. Madore" Date: Mon, 12 Apr 2010 15:30:36 +0200 Subject: Move ad hoc serializer to an "Unparser" class (ugly and unfinished). --- org/madore/damlengine/Unparser.java | 88 +++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 org/madore/damlengine/Unparser.java (limited to 'org/madore/damlengine/Unparser.java') diff --git a/org/madore/damlengine/Unparser.java b/org/madore/damlengine/Unparser.java new file mode 100644 index 0000000..a903523 --- /dev/null +++ b/org/madore/damlengine/Unparser.java @@ -0,0 +1,88 @@ +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(); + } + } + +} -- cgit v1.2.3