Java XML Parse File parseXmlFile(File file)

Here you can find the source of parseXmlFile(File file)

Description

Parse the provided File as XML, decompressing it first if it has a .gz file extension.

License

Apache License

Declaration

public static Document parseXmlFile(File file) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

public class Main {
    /** Parse the provided {@link File} as XML, decompressing it first if it has a .gz file extension. */
    public static Document parseXmlFile(File file) throws IOException {
        InputStream in = toInputStream(file);
        try {/*from  www .j  av a2 s .  c  o m*/
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(in);
        } catch (Exception e) {
            throw new RuntimeException("failed to parse", e);
        } finally {
            in.close();
        }
    }

    private static InputStream toInputStream(File file) throws IOException {
        InputStream in = new FileInputStream(file);
        if (file.getName().endsWith(".gz")) {
            in = new GZIPInputStream(in);
        }
        return in;
    }
}

Related

  1. parseXml(String filename, boolean validating)
  2. parseXml(String filePath)
  3. parseXml(String filePath)
  4. parseXml(String value, boolean isFile)
  5. parseXMLFile(File f)
  6. parseXmlFile(File file, boolean validating)
  7. parseXMLFile(final File xmlFile)
  8. parseXmlFile(String filename, boolean validating)
  9. parseXmlFile(String in)