Java XML Node to String convertToString(Node node)

Here you can find the source of convertToString(Node node)

Description

convert To String

License

Open Source License

Declaration

public static String convertToString(Node node) 

Method Source Code


//package com.java2s;
/*/* w  ww . java  2s . c  o  m*/
 * movie-renamer-core
 * Copyright (C) 2012 Nicolas Magr?
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.StringWriter;

import javax.xml.transform.*;
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.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

public class Main {
    public static String convertToString(Node node) {
        boolean withXMLDeclaration = true;
        String result;
        if (withXMLDeclaration) {
            Document document = node.getOwnerDocument();
            DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
            LSSerializer serializer = domImplLS.createLSSerializer();
            result = serializer.writeToString(node);
        } else {
            try {
                TransformerFactory transFactory = TransformerFactory.newInstance();
                Transformer transformer = transFactory.newTransformer();
                StringWriter buffer = new StringWriter();
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                transformer.transform(new DOMSource(node), new StreamResult(buffer));
                result = buffer.toString();
            } catch (TransformerConfigurationException e) {
                result = "";
            } catch (TransformerException e) {
                result = "";
            }
        }
        return result;
    }
}

Related

  1. asString(Node node)
  2. asString(Node node)
  3. asString(XMLStreamReader xmlr)
  4. asXML(Node node)
  5. asXmlString(Node node)
  6. convertToString(Node node)
  7. createXmlString(Node node)
  8. dump(Node node)
  9. dumpNode(Node node)