/** StreamResult object is re-used and the values are set appropriately. */ StreamResult toStreamResult(OutputStream os, Writer writer, String systemId) { StreamResult sr = new StreamResult(); sr.setOutputStream(os); sr.setWriter(writer); sr.setSystemId(systemId); return sr; }
protected static void createXslFile(String fileName, MappingScript script) throws IOException { File xsltDir = ConfigSingleton.getRepoxContextUtil() .getRepoxManager() .getMetadataTransformationManager() .getXsltDir(); if (!xsltDir.exists()) xsltDir.mkdirs(); File xslFile = new File(xsltDir, fileName.toLowerCase() + XSL_END); StreamResult tmpResult = new StreamResult(new FileOutputStream(xslFile)); XsltStylesheet xslt = new XSLTCompiler(new ToolsetManagerImpl<XsltFunction>(XsltToolsetLibrary.getToolsets())) .compile(script); new XsltWriter().write(xslt, tmpResult); tmpResult.getOutputStream().close(); /* DUMMY FILE CREATION CODE File xsltDir = ConfigSingleton.getRepoxContextUtil().getRepoxManager().getMetadataTransformationManager().getXsltDir(); if(!xsltDir.exists()) xsltDir.mkdirs(); tmpFile = new File(xsltDir, fileName.toLowerCase()+XSL_END); FileWriter fstream = new FileWriter(tmpFile); BufferedWriter outFile = new BufferedWriter(fstream); outFile.write("<This is a dummy xslt>"); outFile.close();*/ // System.out.println("SERVER - XSL created"); }
/** * Apply an XSLT transform to the current XML object in this transaction. * * @throws IllegalStateException if the current root object is null * @throws PersistentObjectException if an error occurs * @throws TransformerException if the transformation fails */ public void transform(Transformer transformer) throws TransformerException { // Sanity check if (this.current == null) throw new PersistentObjectException("no data to transform"); // Debug // System.out.println("************************** BEFORE TRANSFORM"); // System.out.println(this.current); // Set up source and result StreamSource source = new StreamSource(new StringReader(this.current)); source.setSystemId(this.systemId); StringWriter buffer = new StringWriter(BUFFER_SIZE); StreamResult result = new StreamResult(buffer); result.setSystemId(this.systemId); // Apply transform transformer.transform(source, result); // Save result as the new current value this.current = buffer.toString(); // Debug // System.out.println("************************** AFTER TRANSFORM"); // System.out.println(this.current); }
public static String format(String xmlStr) { // Instantiate transformer input Source xmlInput = new StreamSource(new StringReader(xmlStr)); StreamResult xmlOutput = new StreamResult(new StringWriter()); // Configure transformer Transformer transformer; try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e) { logger.error(e.getMessage(), e); return xmlStr; } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block logger.error(e.getMessage(), e); return xmlStr; } // An identity transformer try { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); } catch (TransformerException e) { logger.error(e.getMessage(), e); return xmlStr; } return xmlOutput.getWriter().toString(); }
protected XSLProcessorImpl init(Result result) throws TransformerException { XSLProcessorImpl processor = (XSLProcessorImpl) _processor.clone(); if (result instanceof StreamResult) { StreamResult sr = (StreamResult) result; OutputMethodHandlerImpl outputMethodHandler = new OutputMethodHandlerImpl(); processor.setOutputMethodHandler(outputMethodHandler); Destination dest; OutputStream ostream = sr.getOutputStream(); if (ostream != null) { dest = new OutputStreamDestination(ostream); } else { // FIXME: we need to handle a characterWriter throw new TransformerException("cannot use Writer result"); } outputMethodHandler.setDestination(dest); } else if (result instanceof SAXResult) { SAXResult sr = (SAXResult) result; processor.setContentHandler(sr.getHandler()); // FIXME: set lexical handler? } else { throw new TransformerException("unrecognized Result class: " + result.getClass().getName()); } return processor; }
public static void createXMLFile(Document doc, File file) { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); // write to file // Create file if it does not exist boolean success = file.createNewFile(); if (success) { // File did not exist and was created boolean append = false; FileWriter fw = new FileWriter(file, append); fw.write(xmlString); fw.close(); } else { // File already exists boolean append = false; FileWriter fw = new FileWriter(file, append); fw.write(xmlString); // appends the string to the file fw.close(); } } catch (TransformerException e) { e.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } }
private String transformXml(final Document document) throws TransformerException { final Transformer transformer = XmlUtils.createIndentingTransformer(); final DOMSource source = new DOMSource(document); final StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); return result.getWriter().toString(); }
/** Generate schema. */ public void doSchema(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { setHeaders(rsp); rsp.setContentType("application/xml"); StreamResult r = new StreamResult(rsp.getOutputStream()); new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r); r.getOutputStream().close(); }
public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException { this.file = constructFileLocation(name, SCHEMA, XML); file.getParentFile().mkdirs(); StreamResult result = new StreamResult(file); result.setSystemId(file.toURI().toURL().toString()); return result; }
public void saveCurrentRoute(View view) { if (GPS_captureStarted) { Log.w("Saving Route", "Can't Save, tracking not paused"); return; } Element metadata = gpx_document.createElement("metadata"); Element filename = gpx_document.createElement("name"); Element author = gpx_document.createElement("author"); Element trackName = gpx_document.createElement("name"); String fn = "TestFile"; String tn = "TestTrack"; String auth = "Username"; filename.appendChild(gpx_document.createTextNode(fn)); author.appendChild(gpx_document.createTextNode(auth)); trackName.appendChild(gpx_document.createTextNode(tn)); track.appendChild(trackName); metadata.appendChild(filename); metadata.appendChild(author); rootElement.appendChild(metadata); try { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(gpx_document); StreamResult result; if (isConnected) { result = new StreamResult(new StringWriter()); transformer.transform(source, result); String gpx = result.getWriter().toString(); Request.send_GPX(gpx); } else { FileOutputStream stream = openFileOutput(fn + ".gpx", MODE_PRIVATE); result = new StreamResult(stream); transformer.transform(source, result); Log.i("writing file", "success"); filesToSync.put(fn + ".gpx", true); } } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override public void close() { if (result.getOutputStream() != null) { try { result.getOutputStream().close(); } catch (IOException e) { } } }
public void save(XMLDocument xmlDocument, Result result, Object options) throws IOException { if (xmlDocument == null) { throw new IllegalArgumentException( SDOException.cannotPerformOperationWithNullInputParameter("save", "xmlDocument")); } if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult) result; Writer writer = streamResult.getWriter(); if (null == writer) { save(xmlDocument, streamResult.getOutputStream(), options); } else { save(xmlDocument, writer, options); } } else { // get XMLMarshaller once - as we may create a new instance if this helper isDirty=true XMLMarshaller anXMLMarshaller = getXmlMarshaller(options); // Ask the SDOXMLDocument if we should include the XML declaration in the resulting XML anXMLMarshaller.setFragment(!xmlDocument.isXMLDeclaration()); anXMLMarshaller.setEncoding(xmlDocument.getEncoding()); anXMLMarshaller.setSchemaLocation(xmlDocument.getSchemaLocation()); anXMLMarshaller.setNoNamespaceSchemaLocation(xmlDocument.getNoNamespaceSchemaLocation()); ((SDOMarshalListener) anXMLMarshaller.getMarshalListener()) .setMarshalledObject(xmlDocument.getRootObject()); ((SDOMarshalListener) anXMLMarshaller.getMarshalListener()) .setMarshalledObjectRootQName( new QName(xmlDocument.getRootElementURI(), xmlDocument.getRootElementName())); if (result instanceof SAXResult) { ContentHandlerRecord marshalRecord = new ContentHandlerRecord(); marshalRecord.setContentHandler(((SAXResult) result).getHandler()); marshalRecord.setMarshaller(anXMLMarshaller); ((SDOMarshalListener) anXMLMarshaller.getMarshalListener()) .setRootMarshalRecord(marshalRecord); anXMLMarshaller.marshal(xmlDocument, marshalRecord); } else if (result instanceof DOMResult) { NodeRecord marshalRecord = new NodeRecord(); marshalRecord.setDOM(((DOMResult) result).getNode()); marshalRecord.setMarshaller(anXMLMarshaller); ((SDOMarshalListener) anXMLMarshaller.getMarshalListener()) .setRootMarshalRecord(marshalRecord); anXMLMarshaller.marshal(xmlDocument, marshalRecord); } else { StringWriter writer = new StringWriter(); this.save(xmlDocument, writer, options); String xml = writer.toString(); StreamSource source = new StreamSource(new java.io.StringReader(xml)); anXMLMarshaller.getTransformer().transform(source, result); } } }
public String getText() { String text = null; try { // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); _transformer.transform(new DOMSource(this.document), result); text = result.getWriter().toString(); } catch (Exception e) { e.printStackTrace(); } return text; }
private String createXMLDocument(Document doc) throws TransformerException { Element root = doc.createElement(TESTRUN); root.setAttribute(IGNORED, Integer.valueOf(testResults.ignored).toString()); root.setAttribute(ERRORS, Integer.valueOf(testResults.errors).toString()); root.setAttribute(STARTED, Integer.valueOf(testResults.started).toString()); root.setAttribute(TESTS, Integer.valueOf(testResults.tests).toString()); root.setAttribute("project", testResults.project); root.setAttribute("name", testResults.name); for (Entry<String, Map<String, Set<Test>>> result : testResults.testResults.entrySet()) { Element suite = doc.createElement(TESTSUITE); suite.setAttribute("name", result.getKey()); float suiteTime = 0; for (Entry<String, Set<Test>> configTest : result.getValue().entrySet()) { Element config1 = doc.createElement(TESTSUITE); config1.setAttribute("name", configTest.getKey()); float configTime = 0; for (Test test : configTest.getValue()) { Element testCase = doc.createElement(TESTCASE); testCase.setAttribute("name", test.name); testCase.setAttribute(CLASSNAME, test.classname); testCase.setAttribute(TIME, test.time + ""); if (test.failure != null) { Element failure; if (test.failure.getException() instanceof AssertionError) { failure = doc.createElement(FAILURE); } else { failure = doc.createElement("error"); } failure.setTextContent(test.failure.getTrace()); testCase.appendChild(failure); } config1.appendChild(testCase); configTime += test.time; } suiteTime += configTime; config1.setAttribute(TIME, Double.valueOf(configTime).toString()); suite.appendChild(config1); } suite.setAttribute(TIME, Double.valueOf(suiteTime).toString()); root.appendChild(suite); } doc.appendChild(root); // Transform the Xml Representation into a String Transformer transfo = TransformerFactory.newInstance().newTransformer(); transfo.setOutputProperty(OutputKeys.METHOD, "xml"); transfo.setOutputProperty(OutputKeys.INDENT, YES); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transfo.transform(source, result); return prettyPrint(result.getWriter().toString()); }
/** * Parse and pretty pint a XML content. * * @param content the XML content to format * @return the formated version of the passed XML content * @throws TransformerFactoryConfigurationError when failing to create a {@link * TransformerFactoryConfigurationError} * @throws TransformerException when failing to transform the content * @since 5.2M1 */ public static String formatXMLContent(String content) throws TransformerFactoryConfigurationError, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult result = new StreamResult(new StringWriter()); StreamSource source = new StreamSource(new StringReader(content)); transformer.transform(source, result); return result.getWriter().toString(); }
public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException { if (outputFile != null) { File dir = new File(outputFile.getParent(), SCHEMAS_FOLDER); // $NON-NLS-1$ dir.mkdirs(); file = new File(dir, fileName); } else { file = new File(fileName); } StreamResult result = new StreamResult(file); result.setSystemId(file.toURI().toURL().toString()); return result; }
public File stripXmlFromFile(File xmlFile) throws ParserConfigurationException, IOException, SAXException, TransformerException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = null; doc = db.parse(xmlFile); // doc.getDocumentElement().normalize(); try { System.out.println("Root element " + doc.getDocumentElement().getNodeName()); NodeList nodeLst = doc.getElementsByTagName("sv:property"); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); System.out.println(fstNode.getNodeName()); Element fstElmnt = (Element) fstNode; String attribute = fstElmnt.getAttribute("sv:name"); if (attribute.equals("jcr:uuid")) { Node parent = fstElmnt.getParentNode(); parent.removeChild(fstElmnt); } } } catch (Exception e) { System.out.println(e.getMessage()); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "no"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); System.out.println(xmlString); File parsedXml = new File("./src/test/resources/htmltagstripper/result.xml"); if (parsedXml.exists()) { boolean deleted = parsedXml.delete(); } FileWriter fileWriter = new FileWriter(parsedXml); fileWriter.write(result.getWriter().toString()); fileWriter.flush(); return parsedXml; }
public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()); } catch (Exception e) { return xml; } }
public String toString(SOAPMessage message, int indent) throws IOException, SOAPException, TransformerException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); message.writeTo(baos); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", indent); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); StreamSource streamSource = new StreamSource(new ByteArrayInputStream(baos.toByteArray())); transformer.transform(streamSource, result); return result.getWriter().toString(); }
/** * Print out a SOAPMessage to System.out. * * @param source */ public static void print(final Source source) { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); System.out.println(result.getWriter().toString()); } catch (Exception exception) { System.out.println("Failed to print message: " + exception.getLocalizedMessage()); } }
/** * This method is used to format response xml * * @param input * @param indent * @return */ public static String prettyFormat(String input, int indent) { try { Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Reformats XML text for pretty-printing. * * @param xml The XML text. * @return The formatted XML text. */ public static String format(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()); } catch (IllegalArgumentException | TransformerException | TransformerFactoryConfigurationError ex) { throw new RuntimeException("Failed to format XML", ex); } }
protected static void createXmapFile(String fileName, MappingScript script) throws IOException { File xmapDir = ConfigSingleton.getRepoxContextUtil() .getRepoxManager() .getMetadataTransformationManager() .getXmapDir(); if (!xmapDir.exists()) xmapDir.mkdirs(); File xmapFile = new File(xmapDir, fileName.toLowerCase() + XMAP_END); StreamResult tmpResult = new StreamResult(new FileOutputStream(xmapFile)); new XMLMappingWriter().write(script, tmpResult); tmpResult.getOutputStream().close(); // System.out.println("SERVER - XMAP created"); }
/** Creates new form ViewDataPanel */ public ViewDataPanel(Document document) { initComponents(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(document); transformer.transform(source, result); String xmlString = result.getWriter().toString(); textArea.setText(xmlString); } catch (Exception ex) { ex.printStackTrace(); } }
public static String domToString(org.w3c.dom.Document document) { try { Source xmlSource = new DOMSource(document); StreamResult result = new StreamResult(new ByteArrayOutputStream()); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); // Java XML Indent transformer.transform(xmlSource, result); return result.getOutputStream().toString(); } catch (TransformerFactoryConfigurationError factoryError) { LOG.error("Error creating TransformerFactory", factoryError); } catch (TransformerException transformerError) { LOG.error("Error transforming document", transformerError); } return null; }
public static String prettyPrint(String inString) { try { TransformerFactory factory = TransformerFactory.newInstance(); factory.setAttribute("indent-number", new Integer(4)); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); StreamSource source = new StreamSource(new StringReader(inString)); transformer.transform(source, result); String xmlString = result.getWriter().toString(); return xmlString; } catch (TransformerException ex) { ex.printStackTrace(); } return null; }
public void marshal(Object obj, Result result) throws JAXBException { // XMLSerializable so = Util.toXMLSerializable(obj); XMLSerializable so = context.getGrammarInfo().castToXMLSerializable(obj); if (so == null) throw new MarshalException(Messages.format(Messages.NOT_MARSHALLABLE)); if (result instanceof SAXResult) { write(so, ((SAXResult) result).getHandler()); return; } if (result instanceof DOMResult) { Node node = ((DOMResult) result).getNode(); if (node == null) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); ((DOMResult) result).setNode(doc); write(so, new SAX2DOMEx(doc)); } catch (ParserConfigurationException pce) { throw new JAXBAssertionError(pce); } } else { write(so, new SAX2DOMEx(node)); } return; } if (result instanceof StreamResult) { StreamResult sr = (StreamResult) result; XMLWriter w = null; if (sr.getWriter() != null) w = createWriter(sr.getWriter()); else if (sr.getOutputStream() != null) w = createWriter(sr.getOutputStream()); else if (sr.getSystemId() != null) { String fileURL = sr.getSystemId(); if (fileURL.startsWith("file:///")) { if (fileURL.substring(8).indexOf(":") > 0) fileURL = fileURL.substring(8); else fileURL = fileURL.substring(7); } // otherwise assume that it's a file name try { w = createWriter(new FileOutputStream(fileURL)); } catch (IOException e) { throw new MarshalException(e); } } if (w == null) throw new IllegalArgumentException(); write(so, w); return; } // unsupported parameter type throw new MarshalException(Messages.format(Messages.UNSUPPORTED_RESULT)); }
/** * Formats the json content and print it * * @param xml the xml content */ @Override public void xml(String xml) { if (TextUtils.isEmpty(xml)) { d("Empty/Null xml content"); return; } try { Source xmlInput = new StreamSource(new StringReader(xml)); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(xmlInput, xmlOutput); d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n")); } catch (TransformerException e) { e(e.getCause().getMessage() + "\n" + xml); } }
private static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); // serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, // "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount", // "2"); Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()); } catch (Exception e) { // TODO log error return xml; } }
public void save(File file) throws TransformerException, IOException { OutputStream os = new FileOutputStream(file); StreamResult streamResult; if (gzipOutput) { streamResult = new StreamResult(new GZIPOutputStream(os)); } else { streamResult = new StreamResult(os); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.STANDALONE, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "xml"); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); serializer.transform(new DOMSource(doc), streamResult); streamResult.getOutputStream().close(); }