Java XML Document to String documentToString(Document doc)

Here you can find the source of documentToString(Document doc)

Description

Transforms the given XML document into its textual representation.

License

Open Source License

Parameter

Parameter Description
doc the document to transform.

Exception

Parameter Description
TransformerExceptionif the transformation failed.

Return

the XML document transformed to a string.

Declaration

public static String documentToString(Document doc) throws TransformerException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010-2014 SAP AG and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from   w  w  w . j a v  a 2s. c o m
 *     SAP AG - initial API and implementation
 *******************************************************************************/

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.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class Main {
    /**
     * Transforms the given XML document into its textual representation.
     *
     * @param doc  the document to transform.
     * @return  the XML document transformed to a string.
     *
     * @throws TransformerException  if the transformation failed.
     */
    public static String documentToString(Document doc) throws TransformerException {
        StreamResult result = new StreamResult(new StringWriter());
        transform(doc, result);
        String xmlString = result.getWriter().toString();
        return xmlString;
    }

    private static void transform(Document doc, StreamResult result) throws TransformerException {
        DOMSource source = new DOMSource(doc);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.transform(source, result);
    }
}

Related

  1. document2String(Document doc, boolean prettyPrint)
  2. document2String(Node document)
  3. document2XmlString(Document xmldoc)
  4. documentToString(Document d)
  5. documentToString(Document d)
  6. documentToString(Document doc)
  7. documentToString(Document doc)
  8. documentToString(Document doc)
  9. documentToString(Document doc)