1 5 6 package org.exoplatform.services.jcr.impl.util; 7 8 import java.util.Map ; 9 import java.util.Iterator ; 10 import java.util.Stack ; 11 import java.util.Properties ; 12 import java.util.HashMap ; 13 14 20 21 public class XMLWriter { 22 23 private boolean nsWritten; 24 private Map namespaces; 25 private StringBuffer buffer; 26 private Stack nodes; 27 28 public XMLWriter(Map namespaces) { 29 this.buffer = new StringBuffer (); 30 this.namespaces = namespaces; 31 this.nodes = new Stack (); 32 this.nsWritten = false; 33 } 34 35 public XMLWriter() { 36 this(new HashMap ()); 37 } 38 39 public void startElement(String qname, Properties attrs) { 40 Iterator keys; 41 buffer.append("<" + qname); 42 if (!nsWritten) { 43 keys = namespaces.keySet().iterator(); 44 while (keys.hasNext()) { 45 String key = (String ) keys.next(); 46 String value = (String ) namespaces.get(key); 47 writeAttribute("xmlns:" + key, value); 48 } 49 nsWritten = true; 50 } 51 if (attrs != null) { 52 keys = attrs.keySet().iterator(); 53 while (keys.hasNext()) { 54 String key = (String ) keys.next(); 55 String value = (String ) attrs.get(key); 56 writeAttribute(key, value); 57 } 58 } 59 if (!nodes.empty()) { 60 ((Context) nodes.peek()).isOpen = false; 61 } 62 nodes.push(new Context(qname)); 63 buffer.append(">"); 64 } 65 66 public void endElement() { 67 Context curNode; 68 if (!nodes.empty()) 69 curNode = (Context) nodes.pop(); 70 else 71 throw new RuntimeException ("Unexpected Empty Stack at End element !!"); 72 73 buffer.append("</" + curNode.nodeName + ">"); 78 } 79 80 private void writeAttribute(String qname, String value) { 81 buffer.append(" " + qname + "=\"" + value + "\""); 82 } 83 84 public void writeText(String text) { 85 if (!nodes.empty()) { 86 if (text.length() > 0) 87 ((Context) nodes.peek()).isOpen = false; 88 } else 89 throw new RuntimeException ("Unexpected Empty Stack at Text '" + text + "' !!!"); 90 buffer.append(text); 91 } 92 93 public byte[] getBytes() { 94 return buffer.toString().getBytes(); 95 } 96 97 public String toString() { 98 return buffer.toString(); 99 } 100 101 private class Context { 102 private Context(String nodeName) { 103 this.nodeName = nodeName; 104 this.isOpen = true; 105 } 106 107 private String nodeName; 108 private boolean isOpen; 109 } 110 } 111 | Popular Tags |