8. Write a Java application to validate the XML document using the DOM parser.

PHOTO EMBED

Thu Oct 31 2024 16:16:46 GMT+0000 (Coordinated Universal Time)

Saved by @varuntej #java

java 
Copy code 
import java.io.*;
import javax.xml.parsers.*;

public class DOMValidator {
    public static void main(String[] args) {
        try {
            System.out.println("Enter the XML file name:");
            File file = new File(new BufferedReader(new InputStreamReader(System.in)).readLine());
            if (file.exists() && isWellFormed(file)) {
                System.out.println(file.getName() + " is well-formed.");
            } else {
                System.out.println(file.exists() ? "Not well-formed." : "File not found.");
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    private static boolean isWellFormed(File file) {
        try {
            DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

 
xml 
Copy code 
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>

 
output:XML is valid
content_copyCOPY