Java 怎么从XML节点将DOM输出为流

2019年7月25日22:38:41Java 怎么从XML节点将DOM输出为流已关闭评论 495 1016字阅读3分23秒

1.简介

Java 怎么从XML节点将DOM输出为流?——请看下文。

2.示例代码

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

 

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

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {
    
    public static InputStream documentToPrettyInputStream(Node document)
            throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        Source xmlSource = new DOMSource(document);
        Result outputTarget = new StreamResult(outputStream);
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.transform(xmlSource, outputTarget);

        InputStream is = new ByteArrayInputStream(
                outputStream.toByteArray());
        return is;
    }
}

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