Here you can find the source of writeXML(Document doc, OutputStream os)
Parameter | Description |
---|---|
doc | a parameter |
os | a parameter |
Parameter | Description |
---|---|
TransformerException | an exception |
IOException | an exception |
public static void writeXML(Document doc, OutputStream os) throws TransformerException, IOException
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.Transformer; 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; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /**// ww w .j ava 2 s . c o m * write out an XML file * * @param doc * @param os * @throws TransformerException * @throws IOException */ public static void writeXML(Document doc, OutputStream os) throws TransformerException, IOException { // write out xml file TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); //indent XML properly formatXML(doc, doc.getDocumentElement(), " "); //normalize document doc.getDocumentElement().normalize(); //write XML to file DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(os); transformer.transform(source, result); os.close(); } /** * format XML into human readable form * @param document * @param root * @param tab */ private static void formatXML(Document document, org.w3c.dom.Element root, String tab) { NodeList children = root.getChildNodes(); // save the nodes in the array first Node[] nodes = new Node[children.getLength()]; for (int i = 0; i < children.getLength(); i++) nodes[i] = children.item(i); // insert identations for (int i = 0; i < nodes.length; i++) { root.insertBefore(document.createTextNode("\n" + tab), nodes[i]); if (nodes[i] instanceof org.w3c.dom.Element) formatXML(document, (org.w3c.dom.Element) nodes[i], " " + tab); } root.appendChild(document.createTextNode("\n" + tab.substring(0, tab.length() - 2))); } }