Java examples for XML:DOM
save Dom To File
import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.*; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main{ private static Logger log = Logger.getLogger(DomUtil.class); /************************************************************************** ************ Private Methods ****************** *************************************************************************/ // private static TransformerFactory transFact = TransformerFactory.newInstance(); private static TransformerFactory transFact = TransformerFactory .newInstance();/*from w ww. j a va2 s. c o m*/ public static void saveDomToFile(Node doc, File file) throws IOException { String b = domToString(doc, true); FileUtil.writeToFile(file, b, "UTF-8"); } public static String domToString(Document doc, boolean withXmlDeclaration) { return domToString(doc.getDocumentElement(), withXmlDeclaration); } /** Transforms a DOM into a String * @param doc a DOM Document * @param withXmlDeclaration include the xml declaration? * @return String representation of the DOM */ public static String domToString(Node doc, boolean withXmlDeclaration) { try { // TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = transFact.newTransformer(); if (!withXmlDeclaration) transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes"); DOMSource source = new DOMSource(doc); StringWriter output = new StringWriter(); StreamResult result = new StreamResult(output); transformer.transform(source, result); return output.toString(); } catch (TransformerConfigurationException tce) { // Use the contained exception, if any Throwable x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); log.error(x); } catch (TransformerException te) { // Use the contained exception, if any Throwable x = te; if (te.getException() != null) x = te.getException(); x.printStackTrace(); log.error(x); } return null; } }