Java XML Node to String nodeToString(Node n)

Here you can find the source of nodeToString(Node n)

Description

node To String

License

Open Source License

Declaration

public static String nodeToString(Node n) throws TransformerException 

Method Source Code

//package com.java2s;
/*/*from  w  ww  .j  a  v  a2s. co  m*/
 * Copyright (C) 2006-2016 Talend Inc. - www.talend.com
 * 
 * This source code is available under agreement available at
 * %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
 * 
 * You should have received a copy of the agreement along with this program; if not, write to Talend SA 9 rue Pages
 * 92150 Suresnes, France
 */

import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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.Node;

public class Main {
    private static final TransformerFactory transformerFactory = TransformerFactory.newInstance();

    public static String nodeToString(Node n, boolean isOmitXmlDeclaration, boolean isIndent)
            throws TransformerException {
        StringWriter sw = new StringWriter();
        Transformer transformer = generateTransformer(isOmitXmlDeclaration, isIndent);
        transformer.transform(new DOMSource(n), new StreamResult(sw));
        return sw.toString();
    }

    public static String nodeToString(Node n) throws TransformerException {
        return nodeToString(n, true, true);
    }

    public static Transformer generateTransformer() throws TransformerConfigurationException {
        return transformerFactory.newTransformer();
    }

    public static Transformer generateTransformer(boolean isOmitXmlDeclaration)
            throws TransformerConfigurationException {
        Transformer transformer = generateTransformer();
        if (isOmitXmlDeclaration) {
            transformer.setOutputProperty("omit-xml-declaration", "yes");
        } else {
            transformer.setOutputProperty("omit-xml-declaration", "no");
        }
        return transformer;
    }

    public static Transformer generateTransformer(boolean isOmitXmlDeclaration, boolean isIndent)
            throws TransformerConfigurationException {
        Transformer transformer = generateTransformer(isOmitXmlDeclaration);
        if (isIndent) {
            transformer.setOutputProperty("indent", "yes");
        } else {
            transformer.setOutputProperty("indent", "no");
        }
        return transformer;
    }
}

Related

  1. nodeToString(final Node node)
  2. nodeToString(final Node node)
  3. nodeToString(final Node node)
  4. nodeToString(Node doc)
  5. nodeToString(Node n)
  6. nodeToString(Node n)
  7. nodeToString(Node node)
  8. nodeToString(Node node)
  9. nodeToString(Node node)