Preview:
import java.io.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import org.xml.sax.helpers.DefaultHandler;

public class XMLValidation {
    public static void main(String[] args) {
        try {
            // Prompt user for XML file name
            System.out.println("Enter the XML file name:");
            String filename = new BufferedReader(new InputStreamReader(System.in)).readLine();
            File file = new File(filename);

            // Check if the file exists
            if (file.exists()) {
                validateXML(file);
            } else {
                System.out.println("File not found.");
            }
        } catch (IOException e) {
            System.out.println("Error reading input: " + e.getMessage());
        }
    }

    private static void validateXML(File file) {
        try {
            // Initialize the SAX parser
            SAXParserFactory.newInstance().newSAXParser().parse(file, new DefaultHandler());
            System.out.println(file.getName() + " is valid XML.");
        } catch (Exception e) {
            System.out.println(file.getName() + " is not valid XML.");
        }
    }
}


hello.xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book>
        <title>Java Programming</title>
        <author>John Doe</author>
    </book>
    <book>
        <title>XML Development</title>
        <author>Jane Smith</author>
    </book>
</library>
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter