1 11 package org.eclipse.help.internal.dynamic; 12 13 import java.io.ByteArrayOutputStream ; 14 import java.io.UnsupportedEncodingException ; 15 import java.util.Properties ; 16 17 import javax.xml.transform.OutputKeys ; 18 import javax.xml.transform.Transformer ; 19 import javax.xml.transform.TransformerConfigurationException ; 20 import javax.xml.transform.TransformerException ; 21 import javax.xml.transform.TransformerFactory ; 22 import javax.xml.transform.dom.DOMSource ; 23 import javax.xml.transform.stream.StreamResult ; 24 25 import org.eclipse.help.internal.UAElement; 26 import org.w3c.dom.Document ; 27 import org.w3c.dom.DocumentType ; 28 import org.w3c.dom.Element ; 29 30 public class DocumentWriter { 31 32 private Transformer transformer; 33 34 public String writeString(UAElement element, boolean xmlDecl) throws TransformerException , TransformerConfigurationException { 35 return writeString(element.element, xmlDecl); 36 } 37 38 public String writeString(Element element, boolean xmlDecl) throws TransformerException , TransformerConfigurationException { 39 byte[] bytes = writeBytes(element, xmlDecl); 40 String encoding = transformer.getOutputProperty(OutputKeys.ENCODING); 41 if (encoding == null) { 42 encoding = "UTF-8"; } 44 try { 45 return new String (bytes, encoding); 46 } 47 catch (UnsupportedEncodingException e) { 48 return new String (bytes); 49 } 50 } 51 52 public byte[] writeBytes(UAElement element, boolean xmlDecl) throws TransformerException , TransformerConfigurationException { 53 return writeBytes(element.element, xmlDecl); 54 } 55 56 public byte[] writeBytes(Element element, boolean xmlDecl) throws TransformerException , TransformerConfigurationException { 57 Document document = element.getOwnerDocument(); 58 if (transformer == null) { 59 TransformerFactory factory = TransformerFactory.newInstance(); 60 transformer = factory.newTransformer(); 61 transformer.setOutputProperty(OutputKeys.METHOD, "xml"); } 63 DocumentType docType = document.getDoctype(); 64 Properties props = transformer.getOutputProperties(); 65 if (docType != null) { 66 props.setProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId()); 67 props.setProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId()); 68 } 69 else { 70 props.remove(OutputKeys.DOCTYPE_PUBLIC); 71 props.remove(OutputKeys.DOCTYPE_SYSTEM); 72 } 73 props.setProperty(OutputKeys.OMIT_XML_DECLARATION, xmlDecl ? "no" : "yes"); transformer.setOutputProperties(props); 75 76 DOMSource source = new DOMSource (element); 77 ByteArrayOutputStream out = new ByteArrayOutputStream (); 78 StreamResult result = new StreamResult (out); 79 transformer.transform(source, result); 80 return out.toByteArray(); 81 } 82 } 83 | Popular Tags |