import java.io.File; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; 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."); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document document = builder.parse(xmlFile); NodeList nodeList = document.getElementsByTagName("book"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println("Element Content: " + node.getTextContent()); } } catch (Exception e) { System.out.println("Validation error: " + e.getMessage()); } } } book.xml <?xml version="1.0" encoding="UTF-8"?> <book> <Name>Arun</Name> <Roll>506</Roll> </book> book.xsd <?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="book"> <xsd:complexType> <xsd:sequence> <xsd:element name="Name" type="xsd:string"/> <xsd:element name="Roll" type="xsd:integer"/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>
Preview:
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