Java XML Format formatXML(String xml)

Here you can find the source of formatXML(String xml)

Description

format XML

License

Open Source License

Declaration

public static String formatXML(String xml) 

Method Source Code


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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;

import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

public class Main {
    public static String formatXML(String xml) {
        try {/*www .  jav a 2 s  . c  o m*/
            Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
            StreamResult res = new StreamResult(new ByteArrayOutputStream());
            serializer.transform(xmlSource, res);
            return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray());
        } catch (Exception e) {

            return xml;
        }
    }
}

Related

  1. formattedPrint(Node xml, OutputStream out)
  2. formatXML(byte[] xmlData, int indent)
  3. formatXML(String unformatted)
  4. formatXml(String xml)
  5. formatXml(String xml)
  6. formatXML(Transformer transformer)
  7. formatXMLStr(String xml)
  8. prettifyString(String string)
  9. prettyFormat(String input)