Java 怎么创建一个缩进以漂亮地打印XML

2019年7月29日21:04:07Java 怎么创建一个缩进以漂亮地打印XML已关闭评论 538 1280字阅读4分16秒

1.简介

Java 怎么创建一个缩进以漂亮地打印XML?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.*;

public class Main{
    public static void main(String[] argv) throws Exception{
        String input = "tah1986.com";
        int indent = 2;
        System.out.println(format(input,indent));
    }
    

    public static String format(String input, int indent) {
        try {
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(
                    "{http:
                    String.valueOf(indent));
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        } catch (IllegalArgumentException | TransformerException e) {
            Logging.getInstance().log(XMLHelper.class, e);
            return input;
        }
    }
}

 
继续阅读
编程十万个怎么办