Java 怎么通过转换(Transform)打印XML

2019年7月29日21:05:40Java 怎么通过转换(Transform)打印XML已关闭评论 590 1010字阅读3分22秒

1.简介

Java 怎么通过转换(Transform)打印XML?——请看下文。

2.示例代码

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



import java.io.OutputStream;
import java.io.OutputStreamWriter;

import java.io.UnsupportedEncodingException;
import java.io.Writer;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class Main {
    public static void printXml(Document xml, Writer out)
            throws TransformerException, UnsupportedEncodingException {
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        transformer.transform(new DOMSource(xml), new StreamResult(out));
    }

    public static void printXml(Document response, OutputStream out)
            throws UnsupportedEncodingException, TransformerException {
        printXml(response, new OutputStreamWriter(out));
    }
}

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