Java XML Node to String convertToString(Node node)

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

Description

convert To String

License

Apache License

Declaration

public static String convertToString(Node node) throws ParserConfigurationException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.StringWriter;

public class Main {
    public static String convertToString(Node node) throws ParserConfigurationException {
        return convertDocumentToString(convertToDocument(node));
    }//from   w  w w  .j  a  v  a2s . c  o  m

    /**
     * src:http://www.journaldev.com/1237/java-convert-string-to-xml-document-and-xml-document-to-string
     * @param doc
     * @return
     */
    public static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            // below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static Document convertToDocument(Node node) throws ParserConfigurationException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document newDocument = builder.newDocument();
        newDocument.setXmlStandalone(true);
        Node importedNode = newDocument.importNode(node, true);
        newDocument.appendChild(importedNode);
        return newDocument;
    }
}

Related

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