Build an XML Document from the data read on the given stream - Java XML

Java examples for XML:DOM Document

Description

Build an XML Document from the data read on the given stream

Demo Code


//package com.java2s;
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());
    }//from   w  w w .j  a  va  2 s.c o  m

    /**
     * Build an XML Document from the data read on the given stream
     * @param data A stream from which an XML document can be read
     * @return A Document object equivalent to the XML document read on stream
     */
    public static Document xml(InputStream data) {
        try {
            return xmlBuilder().parse(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Build an XML Document from the data contained in the given String
     * @param data A String containing an XML document
     * @return A Document object equivalent to the XML document in the given String
     */
    public static Document xml(String data) {
        return xml(new ByteArrayInputStream(data.getBytes()));
    }

    /**
     * Create a new, empty XML document
     * @return A new, empty XML document
     */
    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();
    }
}

Related Tutorials