Java 怎么通过转换器(Transformer)缩进输出XML

2019年7月29日20:49:39Java 怎么通过转换器(Transformer)缩进输出XML已关闭评论 657 842字阅读2分48秒

1.简介

Java 怎么通过转换器(Transformer)缩进输出XML?——请看下文。

2.示例代码

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


import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import javax.xml.transform.OutputKeys;
import org.w3c.dom.Node;

import java.io.Writer;

public class Main {
    public static void outputXML(Node e, Writer w) throws Exception {
        outputXML(e, w, 4);
    }

    public static void outputXML(Node e, Writer w, int indent)
            throws Exception {
        
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", new Integer(indent));
        Transformer xformer = tf.newTransformer();

        DOMSource source = new DOMSource(e);
        StreamResult result = new StreamResult(w);
        xformer.setOutputProperty(OutputKeys.METHOD, "xml");
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.transform(source, result);
    }
}

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