Java XML Document Format format(Document document)

Here you can find the source of format(Document document)

Description

formats XML with proper indentation

License

Open Source License

Parameter

Parameter Description
document represents the XML to be formatted

Exception

Parameter Description
IOException thrown if formatting fails - usually due to aninvalid object

Return

String of properly formatted XML text

Declaration

public static String format(Document document) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

import java.io.StringWriter;

import java.io.Writer;
import org.w3c.dom.Document;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class Main {
    /**//from  w ww  . j a  v a2 s.com
     * formats XML with proper indentation
     * 
     * @param document represents the XML to be formatted
     * @return String of properly formatted XML text
     * @throws IOException thrown if formatting fails - usually due to an
     *             invalid object
     */
    public static String format(Document document) throws IOException {
        OutputFormat format = new OutputFormat(document);
        format.setLineWidth(65);
        format.setIndenting(true);
        format.setIndent(2);
        Writer out = new StringWriter();
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(document);

        return out.toString();
    }
}

Related

  1. format(Document doc)
  2. format(Document doc)
  3. format(Source xslSource, Document xml, URIResolver resolver)
  4. formatElementEnd( Document document, Element element, String formatString)
  5. formatElementStart( Document document, Element element, String formatString)
  6. formatNode(Document doc, Node parent, Node node)