Java XML Node to String toXml(Node node)

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

Description

to Xml

License

Open Source License

Declaration

public static String toXml(Node node) throws TransformerException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.StringWriter;

import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import org.w3c.dom.Node;

public class Main {
    public static String toXml(Node node) throws TransformerException {
        Source src = new DOMSource(node);
        return toXml(src, -1);
    }//  ww w .  ja va  2  s . co  m

    public static String toXml(XMLStreamReader xml) throws TransformerException {
        Source src = new StAXSource(xml);
        return toXml(src, -1);
    }

    public static String toXml(Source src, int indent)
            throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {
        Transformer transformer = buildXmlTransformer();
        if (indent >= 0) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
        }

        StringWriter writer = new StringWriter();

        Result dest = new StreamResult(writer);
        transformer.transform(src, dest);

        return writer.getBuffer().toString();
    }

    public static String toXml(Document xmlDocument) throws TransformerException {
        return toXml(xmlDocument.getDocumentElement());
    }

    private static Transformer buildXmlTransformer()
            throws TransformerFactoryConfigurationError, TransformerConfigurationException {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        return transformer;
    }
}

Related

  1. toWellKnowName(Node vertexStyleNode)
  2. toWriter(Node node, Writer writer, Map outputProperties)
  3. toXML(Node node)
  4. toXML(Node node)
  5. toXml(Node node)
  6. toXml(Node node, boolean keepHeader)
  7. toXMLString(final Node value)
  8. toXMLString(Node node)
  9. toXMLString(Node node)