Java 怎么从给定流上读取数据生成XML文档(Document)

2019年7月29日19:31:18Java 怎么从给定流上读取数据生成XML文档(Document)已关闭评论 470 1050字阅读3分30秒

1.简介

Java 怎么从给定流上读取数据生成XML文档(Document)?——请看下文。

2.示例代码

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


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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(xml());
    }

    
    public static Document xml(InputStream data) {
        try {
            return xmlBuilder().parse(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    
    public static Document xml(String data) {
        return xml(new ByteArrayInputStream(data.getBytes()));
    }

    
    public static Document xml() {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        try {
            Document d = factory.newDocumentBuilder().newDocument();
            d.setXmlStandalone(true);
            return d;
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
    }

    private static DocumentBuilder xmlBuilder()
            throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        return factory.newDocumentBuilder();
    }
}

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