Java XML Node to String getXml(Node node)

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

Description

Returns a string that represents the given node.

License

Open Source License

Parameter

Parameter Description
node Node to return the XML for.

Return

Returns an XML string.

Declaration

public static String getXml(Node node) 

Method Source Code

//package com.java2s;

import org.w3c.dom.Node;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.StringWriter;

public class Main {
    /**//from w  w w .  j av a 2s .co m
     * Returns a string that represents the given node.
     *
     * @param node Node to return the XML for.
     * @return Returns an XML string.
     */
    public static String getXml(Node node) {
        try {
            Transformer tf = TransformerFactory.newInstance()
                    .newTransformer();

            tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

            StreamResult dest = new StreamResult(new StringWriter());
            tf.transform(new DOMSource(node), dest);

            return dest.getWriter().toString();
        } catch (Exception e) {
            // ignore
        }

        return "";
    }
}

Related

  1. getStringFromDocument(Node doc)
  2. getStringFromNode(Node node)
  3. getStringFromNode(Node node)
  4. getStringFromXML(Node node)
  5. getText(final Node node)
  6. getXmlAsString(Node node)
  7. getXMLString(Node doc)
  8. getXmlString(Node n)
  9. getXMLString(Node node, boolean omitXmlDeclaration)