Java XML Document from File read(String file)

Here you can find the source of read(String file)

Description

read local file

License

Open Source License

Parameter

Parameter Description
file local file name

Exception

Parameter Description
Exception an exception

Return

document

Declaration

public static Document read(String file) throws Exception 

Method Source Code

//package com.java2s;
/**/*from   w ww . j ava 2s  .c  om*/
 * Copyright 2017 Institute of Computing Technology, Chinese Academy of Sciences.
 * Licensed under the terms of the Apache 2.0 license.
 * Please see LICENSE file in the project root for terms
 */

import org.w3c.dom.Document;

import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import java.io.File;
import java.io.InputStream;
import java.io.StringReader;

public class Main {
    /**
     * read local file
     *
     * @param file local file name
     * @return document
     * @throws Exception
     */
    public static Document read(String file) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document dom = builder.parse(new File(file));
        return dom;
    }

    /**
     * Read a xml
     *
     * @param in target inputStream
     * @return document
     * @throws Exception
     */
    public static Document read(InputStream in) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        builder = factory.newDocumentBuilder();
        Document dom = builder.parse(in);
        return dom;
    }

    /** Parse a XML document from string */
    public static Document parse(String xml) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        return builder.parse(is);
    }
}

Related

  1. loadXmlDocumentFromFile(@Nonnull File file)
  2. loadXmlFromFile(String xmlFileName)
  3. read(InputStream input)
  4. read(InputStream xml)
  5. read(java.io.File file)
  6. read(String filename)
  7. readDocument(String fileName)
  8. readDocumentXML(File file)
  9. readXml(File file)