Home  >  Article  >  Java  >  How to determine whether a file is in xml format in java

How to determine whether a file is in xml format in java

王林
王林Original
2019-11-21 14:26:423757browse

How to determine whether a file is in xml format in java

Additional knowledge points:

DocumentBuilderFactory is a parser object used to create DOM patterns. DocumentBuilderFactory is an abstraction Factory class, which provides a newInstance method, which will automatically create and return a factory object based on the parser installed by default on the local platform.

parse()The method is used to parse the XML document and obtain the Document object representing the entire document.

Judge whether the file is in XML format

You can judge by the file extension, but there is no guarantee that the file extension is correct but the content is not in XML format, so you can use Judgment of exceptions.

Example:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
private static boolean isXmlDocument(File file){
    boolean flag = true;
    try {
        DocumentBuilderFactory foctory =DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = foctory.newDocumentBuilder();
        builder.parse(file);
        flag = true;
    } catch (Exception e) {
        flag = false;
    } 
    return flag;
}

Recommended tutorial:Getting started with java development

The above is the detailed content of How to determine whether a file is in xml format in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn