1 /*
2 * Created on Feb 24, 2004
3 *
4 */
5 package jsdsi.xml;
6
7 import jsdsi.sexp.Sexp;
8 import jsdsi.sexp.SexpList;
9 import jsdsi.sexp.SexpOutput;
10 import jsdsi.sexp.SexpString;
11 import java.io.FilterWriter;
12 import java.io.Writer;
13 import java.io.IOException;
14 import java.util.Iterator;
15
16 /***
17 * @author Sameer Ajmani
18 **/
19 public class XmlWriter extends FilterWriter
20 implements SexpOutput
21 {
22 static final String starTagPrefix = "star";
23 private static final String indentation = " ";
24 private static final int width = 72;
25 /***
26 * @param out
27 */
28 public XmlWriter(Writer out) {
29 super(out);
30 }
31 public void writeSexp(Sexp o) throws IOException {
32 write(o, 0);
33 }
34 private static int indentSize(int depth) {
35 return depth * indentation.length();
36 }
37 private void indent(int depth) throws IOException {
38 for (int i = 0; i < depth; i++) {
39 write(indentation);
40 }
41 }
42 private void write(String s, int depth) throws IOException {
43 indent(depth);
44 out.write(s);
45 }
46 private void write(Sexp o, int depth) throws IOException {
47 if (o instanceof SexpList) {
48 SexpList l = (SexpList)o;
49 Iterator i = l.iterator();
50 i.next(); // skip type
51 String type = l.getType();
52 if (type.startsWith("*")){
53 if (type.equals("*") && i.hasNext()) {
54 // (* set ...)
55 type = starTagPrefix + i.next().toString();
56 } else {
57 // (*) or (*set ...) [no space]
58 type = starTagPrefix + type.substring(1);
59 }
60 }
61 if (!i.hasNext()) {
62 write("<"+type+"/>\n", depth);
63 return;
64 }
65 write("<"+type+">\n", depth);
66 while (i.hasNext()) {
67 write((Sexp)i.next(), depth+1);
68 }
69 write("</"+type+">\n", depth);
70 } else {
71 SexpString s = (SexpString)o;
72 indent(depth);
73 s.writeReadable(out, indentSize(depth), width, 0);
74 out.write("\n");
75 }
76 }
77 }
This page was automatically generated by Maven