1 package org.oddjob.arooa.handlers; 2 3 import java.io.OutputStream ; 4 import java.io.PrintWriter ; 5 6 import org.oddjob.arooa.ArooaHandler; 7 import org.oddjob.arooa.ArooaContext; 8 import org.xml.sax.Attributes ; 9 10 13 public class XmlHandler extends ArooaHandler { 14 15 private final PrintWriter out; 16 private final int level; 17 private boolean hadChild; 18 private boolean lastWasText; 19 20 XmlHandler(PrintWriter out, int level) { 21 this.out = out; 22 this.level = level; 23 } 24 25 30 public XmlHandler(OutputStream out) { 31 this.out = new PrintWriter (out); 32 level = 0; 33 } 34 35 public void onStartElement(String uri, String tag, String qname, 36 Attributes attrs, 37 ArooaContext context) { 38 indent(); 39 out.print("<" + tag); 40 for (int i =0; i < attrs.getLength(); ++i) { 41 if (i != 0) { 42 out.println(""); 43 indent(); 44 indent(tag.length() + 1); 45 } 46 indent(1); 47 out.print(attrs.getQName(i)); 48 out.print("=\""); 49 out.print(attrs.getValue(i)); 50 out.print('"'); 51 } 52 } 53 54 public ArooaHandler onStartChild(String uri, String tag, String qname, 55 Attributes attrs, 56 ArooaContext context) { 57 if (!hadChild) { 58 out.println(">"); 59 hadChild = true; 60 } 61 lastWasText = false; 62 return new XmlHandler(out, level + 1); 63 } 64 65 public void onEndElement(String uri, String tag, 66 ArooaContext context) { 67 if (hadChild) { 68 if (!lastWasText) { 69 indent(); 70 } 71 out.println("</" + tag + ">"); 72 } 73 else { 74 out.println("/>"); 75 } 76 out.flush(); 77 } 78 79 public void characters(char[] buf, int start, int count, ArooaContext context) { 80 String s = new String (buf, start, count); 81 s = s.trim(); 82 if (s.length() == 0) { 83 return; 84 } 85 if (!hadChild) { 86 out.print(">"); 87 hadChild = true; 88 } 89 out.write(buf, start, count); 90 lastWasText = true; 91 } 92 93 void indent() { 94 indent(level * 4); 95 } 96 97 void indent(int i) { 98 while (i-- > 0) { 99 out.print(' '); 100 101 } 102 } 103 } 104 105 | Popular Tags |