Java 怎么通过Transformer打印XML文档(Document)

2019年7月29日19:25:02Java 怎么通过Transformer打印XML文档(Document)已关闭评论 1,168 1432字阅读4分46秒

1.简介

Java 怎么通过Transformer打印XML文档(Document)?——请看下文。

2.示例代码

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

 
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Hashtable;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        String input = "tah1986.com";
        System.out.println(prettyPrint(input));
    }
    private static Transformer normalizerTransformer = null;
    private static Transformer serializerTransformer = null;
    private static Logger logger = Logger.getLogger(XmlUtil.class);
    public static String prettyPrint(String input) {
        if ((normalizerTransformer != null)
                && (serializerTransformer != null)) {
            try {
                Source source = new StreamSource(new StringReader(input));
                Writer writer = new StringWriter();

                

                
                DOMResult result = new DOMResult();
                normalizerTransformer.transform(source, result);
                source = new DOMSource(result.getNode());

                
                serializerTransformer.transform(source, new StreamResult(
                        writer));

                return writer.toString();
            } catch (TransformerException e) {
                logger.error("Error pretty printing xml.", e);
            }
        }

        return input;
    }
}

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