Java XML Document Format prettyPrint(Document doc)

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

Description

pretty Print

License

Open Source License

Declaration

public static String prettyPrint(Document doc) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011 IBM Corporation./* www  .  j a  v a  2 s.  com*/
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 *  
 *  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
 *  and the Eclipse Distribution License is available at
 *  http://www.eclipse.org/org/documents/edl-v10.php.
 *  
 *  Contributors:
 *  
 *     IBM Corporation - 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 {
    public static String prettyPrint(Document doc) {
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer serializer;
        StringWriter writer = new StringWriter();
        try {
            serializer = tfactory.newTransformer();
            //Setup indenting to "pretty print"
            serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$

            serializer.transform(new DOMSource(doc), new StreamResult(writer));
            return writer.toString();
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. formatXML(Document document, org.w3c.dom.Element root, String tab)
  2. formatXML(Document xml, Document xsl)
  3. formatXML(Document xml, Document xsl, URIResolver resolver, Writer output)
  4. pretty(Document document, OutputStream outputStream, int indent)
  5. prettyFormat(Document doc)
  6. prettyPrint(Document doc, String programID, String xmlTraDestinationFolderPath)
  7. prettyPrint(final Document aNode)
  8. prettyPrintXml(Document doc)
  9. prettyPrintXml(Document document)