Java tutorial
//package com.java2s; /* infoScoop OpenSource * Copyright (C) 2010 Beacon IT Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0-standalone.html>. */ import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Node; public class Main { /** * convert node object into String object. * * @param node * @return String */ public static String dom2String(Node node) { return dom2String(node, false); } /** * convert node object into String object. * @param node * @param omitXmlDecl * @return */ public static String dom2String(Node node, boolean omitXmlDecl) { Source source = new DOMSource(node); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); if (omitXmlDecl) transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException(e); } return stringWriter.getBuffer().toString(); } }