Java XML Node to String nodeToString(Node node)

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

Description

This method serializes a Node into a String

License

Apache License

Parameter

Parameter Description
node a parameter

Return

String representation of the node

Declaration

public static String nodeToString(Node node) 

Method Source Code

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

import java.io.StringWriter;

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 org.w3c.dom.Node;

public class Main {
    /**//from  w  ww.  j  a v a 2  s .  co  m
     * This method serializes a Node into a String
     * 
     * @param node
     * @return String representation of the node
     */
    public static String nodeToString(Node node) {
        try {

            if (node != null
                    && node.getLocalName().equals(
                            "temporary-simple-type-wrapper")) {
                // this is a temporary hack for string variables and the likes,
                // as you may see ODE wrappes simpletypes in wrapper-elements,
                // but this isn't great here
                return node.getTextContent();
            }

            // Create transformer
            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            // Transform Node into a String representation by regarding some
            // formatting rules
            StringWriter stringWriter = new StringWriter();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(
                    "{http://xml.apache.org/xslt}indent-amount", "3");
            transformer.transform(new DOMSource(node), new StreamResult(
                    stringWriter));

            // Return build string
            return stringWriter.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // If any error occurs, return empty string
        return "";
    }
}

Related

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