Java XML Format format(String unformattedXml)

Here you can find the source of format(String unformattedXml)

Description

format

License

BSD License

Declaration

public static String format(String unformattedXml) 

Method Source Code


//package com.java2s;
/*/*  w w w. j  a va2s .  c om*/
 * The contents of this file are subject to the license and copyright
 * detailed in the LICENSE and NOTICE files at the root of the source
 * tree and available online at
 *
 * http://www.dspace.org/license/
 */

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class Main {
    static final TransformerFactory factory = TransformerFactory.newInstance();

    public static String format(String unformattedXml) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Transformer transformer;
            transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //initialize StreamResult with File object to save to file
            StreamResult result = new StreamResult(out);
            StreamSource source = new StreamSource(new ByteArrayInputStream(unformattedXml.getBytes()));
            transformer.transform(source, result);
            return out.toString();
        } catch (Exception e) {
            return "";
        }
    }
}

Related

  1. applyTransformation(InputStream xsltStream, Map xsltParameters, InputStream inputXmlStream, OutputStream outputStream)
  2. format(final String xml)
  3. format(Node node)
  4. format(Node node, String indent)
  5. formatAttributes(Node node)
  6. formattedPrint(Node xml, OutputStream out)
  7. formatXML(byte[] xmlData, int indent)
  8. formatXML(String unformatted)