Java XML Node to String nodeToXmlString(Node node)

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

Description

Returns an XML representation of the provided node.

License

Apache License

Parameter

Parameter Description
node the node to be represented in XML.

Return

a string containing an XML representation of the provided DOM node.

Declaration

public static String nodeToXmlString(Node node) 

Method Source Code

//package com.java2s;
/*//from  ww  w.  j a  va2  s . c o m
 *
 * $Date$
 * $Author$
 * $Revision$
 *
 * Copyright 2010 the University of New Mexico.
 *
 * This work was supported by National Science Foundation Cooperative
 * Agreements #DEB-0832652 and #DEB-0936498.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 *
 */

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {
    /**
     * Returns an XML representation of the provided node.
     *
     * @param node the node to be represented in XML.
     *
     * @return a string containing an XML representation of the
     * provided DOM node.
     */
    public static String nodeToXmlString(Node node) {

        try {

            Transformer t = TransformerFactory.newInstance().newTransformer();
            t.setOutputProperty(OutputKeys.INDENT, "yes");

            DOMSource source = new DOMSource(node);
            StreamResult result = new StreamResult(new StringWriter());

            t.transform(source, result);

            return result.getWriter().toString();

        } catch (TransformerException e) {
            throw new IllegalStateException(e);
        } catch (TransformerFactoryConfigurationError e) {
            throw new IllegalStateException(e);
        }

    }
}

Related

  1. nodeToString(Node node, StringBuffer sb)
  2. nodeToString(Object node)
  3. nodeToString(org.w3c.dom.Node domNode)
  4. nodeToText(Node node)
  5. nodeToWriter(Node node, Writer writer)
  6. stringifyNode(Node node)
  7. toHtml(StringBuffer html, Node node)
  8. toString(final Node node)
  9. toString(final Node node)