summaryrefslogtreecommitdiffstats
path: root/org/madore/damlengine/Unparser.java
blob: a9035234c62988c43f23aafbd43ba19fcad3b6f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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("<!--(comment)-->");
		skip();
	    } else if ( cursor.getNodeType() == Node.CDATA_SECTION_NODE ) {
		out.write("<![CDATA[(cdata)]]>");
		skip();
	    } else {
		out.write("<!--(some other kind of node)-->");
		skip();
	    }
	    break;
	case POPPING:
	    if ( cursor.getNodeType() == Node.ELEMENT_NODE ) {
		Element elt = (Element)cursor;
		out.write("</"+elt.getTagName()+">");
	    }
	    skip();
	    break;
	}
    }

    public void unparse()
	throws IOException {
	while ( cursor != null ) {
	    unparseOne();
	}
    }

}