Java 怎么解析为XML文档(Document)

2019年7月28日21:57:13Java 怎么解析为XML文档(Document)已关闭评论 524 1069字阅读3分33秒

1.简介

Java 怎么解析为XML文档(Document)?——请看下文。

2.示例代码

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

 

import java.io.*;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import org.w3c.dom.*;

public class Main {
    public static Document parseToDocument(InputStream is,
            boolean debugModeEnabled) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(is);

        if (debugModeEnabled)
            System.out.println("Body:\n" + serializeDocument(document)
                    + "\n");

        return document;
    }

    public static String serializeDocument(Document document)
            throws Exception {
        
        StringWriter writer = new StringWriter();
        StreamResult streamResult = new StreamResult(writer);

        DOMSource domSource = new DOMSource(document);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.transform(domSource, streamResult);

        return writer.toString();
    }
}

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