Java XML Document Create createDocument(final File file)

Here you can find the source of createDocument(final File file)

Description

create Document

License

Apache License

Parameter

Parameter Description
file The XML file to parse.

Exception

Parameter Description
IOException <ul><li>If there is an error finding or reading from the file.</li></ul>
SAXException <ul><li>If the file does not contain valid a XML document.</li></ul>

Return

A new DOM Document with the contents of the given XML file.

Declaration

public static Document createDocument(final File file) throws IOException, SAXException 

Method Source Code


//package com.java2s;
/* //from   w ww  . j  a  va  2 s  .  c o  m
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

import java.net.URI;

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

import org.w3c.dom.Document;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {
    private static final ThreadLocal<?> tls = new ThreadLocal<Object>() {
        // CTw for handling code that sets the context classloader when the TLS is used from a different thread context classloader.
        // "this" is used as the initialization occurs on the correct classloader. The current context classloader also can't be garaunteed.
        ClassLoader cl = Thread.currentThread().getContextClassLoader();

        @Override
        protected Object initialValue() {

            // CTw fix for classloaders
            final ClassLoader ct = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(cl);
            try {

                //1
                // create the builder that will be shared throughout the process
                //
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

                //
                // don't forget - turn on namespaces!!!
                //
                factory.setNamespaceAware(true);

                //
                // we don't need comment nodes - they'll only slow us down
                //
                factory.setIgnoringComments(true);

                try {
                    return factory.newDocumentBuilder();
                }

                //
                // this exception would be thrown if you have the DOM interfaces 
                // but not the implementation
                //
                catch (final ParserConfigurationException error) {
                    throw new RuntimeException(error.getMessage(), error);
                }
            } finally {
                // reset it
                Thread.currentThread().setContextClassLoader(ct);
            }
        }
    };

    /**
     * @return A new DOM Document.
     */
    public static Document createDocument() {
        return createBuilder().newDocument();
    }

    /**
     * @param file
     *            The XML file to parse.
     * @return A new DOM Document with the contents of the given XML file.
     * @throws IOException
     *             <ul>
     *             <li>If there is an error finding or reading from the file.</li>
     *             </ul>
     * @throws SAXException
     *             <ul>
     *             <li>If the file does not contain valid a XML document.</li>
     *             </ul>
     */
    public static Document createDocument(final File file) throws IOException, SAXException {
        return createBuilder().parse(file);
    }

    /**
     * @param source
     *            A SAX InputSource that points to a valid XML document.
     * @return A new DOM Document with the contents of the given XML data.
     * @throws IOException
     *             <ul>
     *             <li>If there is an error reading the data from the source;
     *             this exception is usually generated when the input source is
     *             file or network-based.</li>
     *             </ul>
     * @throws SAXException
     *             <ul>
     *             <li>If the stream does not contain a valid XML document.</li>
     *             </ul>
     */
    public static Document createDocument(final InputSource source) throws IOException, SAXException {
        return createBuilder().parse(source);
    }

    /**
     * @param stream
     *            A stream containing a valid XML document.
     * @return A new DOM Document with the contents of the given XML data.
     * @throws IOException
     *             <ul>
     *             <li>If there is an error reading the bytes in the stream;
     *             this exception is usually generated when the input source is
     *             file or network-based.</li>
     *             </ul>
     * @throws SAXException
     *             <ul>
     *             <li>If the stream does not contain a valid XML document.</li>
     *             </ul>
     */
    public static Document createDocument(final InputStream stream) throws IOException, SAXException {
        return createBuilder().parse(stream);
    }

    /**
     * @param xml
     *            A string containing a valid XML document.
     * @return A new DOM Document with the contents of the given XML string.
     * @throws IOException
     *             <ul>
     *             <li>If there is an error reading the bytes in the string,
     *             which is highly unlikely; this exception is usually generated
     *             when the input source is file or network-based.</li>
     *             </ul>
     * @throws SAXException
     *             <ul>
     *             <li>If the string does not contain a valid XML document.</li>
     *             </ul>
     */
    public static Document createDocument(final String xml) throws IOException, SAXException {
        //
        // have to convert the string to bytes in order to parse it
        //
        final InputSource source = new InputSource(new StringReader(xml));
        return createDocument(source);
    }

    /**
     * This is a convenience method that converts the given URI to a File
     * and invokes createDocument(File).
     * 
     * @param uri
     *            The URI of the XML file to parse.
     * @see #createDocument(File)
     */
    public static Document createDocument(final URI uri) throws IOException, SAXException {
        return createDocument(new File(uri));
    }

    /**
     * @return A new DocumentBuilder, which can be used to parse XML
     *         by <b>a single thread.</b> Because DocumentBuilder.parse() is
     *         <b>not</b> thread-safe
     *         the calling code should not share the document builder (or its
     *         Documents) across threads.
     *         The backing ThreadLocal ensures quick re-use, as such this
     *         function should be called for each
     *         operation on a DocumentBuilder.
     */
    private static DocumentBuilder createBuilder() {
        return (DocumentBuilder) tls.get();
    }
}

Related

  1. createDocument(boolean isSecureProcessing)
  2. createDocument(boolean validating, boolean namespaceAware)
  3. createDocument(byte[] data)
  4. createDocument(File file)
  5. createDocument(File file)
  6. createDocument(final String rootName)
  7. createDocument(InputSource is)
  8. createDocument(Node node)
  9. createDocument(Node sourceNode)