Writing nested CDATA in XML and reuse of DocumentBuilder
XmlHelper Class:
package com.jaspersoft.jasperserver.ws.xml; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class XmlHelper { private static final ThreadLocalCaller class:docBuilder = new ThreadLocal () { @Override protected DocumentBuilder initialValue() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } return builder; } }; private static final ThreadLocal transformer = new ThreadLocal () { @Override protected Transformer initialValue() { TransformerFactory factory = TransformerFactory.newInstance("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl", Thread.currentThread().getContextClassLoader()); Transformer trans = null; try { trans = factory.newTransformer(); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } return trans; } }; public static String getXMLFromDocument(Document document) { Transformer transformer = XmlHelper.getTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StreamResult streamResult = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(document); try { transformer.transform(source, streamResult); } catch (TransformerException e) { e.printStackTrace(); return ""; } XmlHelper.resetTransformer(); return streamResult.getWriter().toString(); } public static DocumentBuilder getDocumentBuilder(){ return XmlHelper.docBuilder.get(); } public static void resetDocumentBuilder(){ getDocumentBuilder().reset(); } public static Transformer getTransformer(){ return XmlHelper.transformer.get(); } public static void resetTransformer(){ getTransformer().reset(); } }
Document document = XmlHelper.getDocumentBuilder().newDocument(); Element rootElement = document.createElement("value"); rootElement.appendChild(document.createCDATASection(value)); document.appendChild(rootElement); String xmlString = XmlHelper.getXMLFromDocument(document); xml.append(currentIndentation + xmlString + "\n"); XmlHelper.resetDocumentBuilder();
留言
張貼留言