3 import java.io.OutputStream;
4 import java.io.OutputStreamWriter;
5 import java.io.UnsupportedEncodingException;
6 import java.util.Stack;
8 import javax.xml.transform.OutputKeys;
9 import javax.xml.transform.Transformer;
10 import javax.xml.transform.TransformerConfigurationException;
11 import javax.xml.transform.TransformerFactoryConfigurationError;
12 import javax.xml.transform.sax.SAXTransformerFactory;
13 import javax.xml.transform.sax.TransformerHandler;
14 import javax.xml.transform.stream.StreamResult;
16 import org.xml.sax.SAXException;
17 import org.xml.sax.helpers.AttributesImpl;
19 public class SimpleXmlGenerator
21 TransformerHandler handler_;
22 Stack<String> openElements_ = new Stack<String>();
24 public SimpleXmlGenerator(OutputStream os, String encoding)
25 throws UnsupportedEncodingException
27 SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory
29 // factory.setAttribute("indent-number", new Integer(2));
31 handler_ = factory.newTransformerHandler();
33 catch (TransformerConfigurationException e) {
34 throw new AssertionError("XML/SAX transformer configuration error");
36 catch (TransformerFactoryConfigurationError e) {
37 throw new AssertionError(
38 "XML/SAX transformer factory configuration error");
40 Transformer tf = handler_.getTransformer();
41 tf.setOutputProperty(OutputKeys.ENCODING, encoding);
42 // if (doctype != null)
43 // tf.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,doctype);
44 // tf.setOutputProperty(OutputKeys.INDENT,indent ? "yes" : "no");
45 handler_.setResult(new StreamResult(
46 new OutputStreamWriter(os, encoding)));
49 public void startDocument() throws SAXException
51 handler_.startDocument();
54 public void start(String name) throws SAXException
56 handler_.startElement("", "", name, null);
57 openElements_.add(name);
60 public static class Attributes
62 AttributesImpl attributes_ = new AttributesImpl();
64 public Attributes attribute(String name, String value)
66 attributes_.addAttribute("", "", name, "CDATA", value);
70 AttributesImpl getAttributes()
79 public Attributes attribute(String name, String value)
81 Attributes a = new Attributes();
82 return a.attribute(name, value);
85 public void start(String name, Attributes attrs) throws SAXException
87 handler_.startElement("", "", name, attrs.getAttributes());
88 openElements_.push(name);
91 public void end() throws SAXException
93 handler_.endElement("", "", openElements_.pop());
96 public void empty(String name) throws SAXException
102 public void empty(String name, Attributes attrs) throws SAXException
108 public void text(String text) throws SAXException
110 handler_.characters(text.toCharArray(), 0, text.length());
113 public void nl() throws SAXException
118 public void endDocument() throws SAXException
120 handler_.endDocument();