9. Write a Java application to validate the XML document using the SAX parser.
Fri Nov 15 2024 15:25:14 GMT+0000 (Coordinated Universal Time)
Saved by
@webtechnologies
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXValidator {
public static void main(String[] args) {
String xmlFilePath = "C:\\Users\\91630\\OneDrive\\Desktop\\Web_technologies_lab\\Book\\book.xml";
String xsdFilePath = "C:\\Users\\91630\\OneDrive\\Desktop\\Web_technologies_lab\\Book\\book.xsd";
File xmlFile = new File(xmlFilePath);
File xsdFile = new File(xsdFilePath);
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsdFile);
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
saxFactory.setSchema(schema);
SAXParser parser = saxFactory.newSAXParser();
parser.parse(xmlFile, new DefaultHandler() {
@Override
public void error(SAXParseException e) {
System.out.println("Validation Error: " + e.getMessage());
}
});
System.out.println("XML file is valid according to the schema.");
} catch (Exception e) {
System.out.println("Validation error: " + e.getMessage());
}
}
}
content_copyCOPY
Comments