1. For validation of your XML file first you have to define Schema (XSD) file
2. After that by using Javax.xml.validation.validator we can validate our XML file.
My XML Schema
- <?xml version="1.0" encoding="UTF-8"?>
- <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
- <xs:element name="destination" type="Destination"/>
- <xs:complexType name="Destination">
- <xs:sequence>
- <xs:element name="name" type="xs:string"/>
- <xs:element name="destinationID" type="xs:string" minOccurs="0"/>
- <xs:element name="shortDescription" type="xs:string" minOccurs="0"/>
- <xs:element name="longDescription" type="xs:string" minOccurs="0"/>
- <xs:element name="stateID" type="xs:string"/>
- <xs:element name="typeCode" type="xs:int"/>
- <xs:element name="countryCode" type="xs:string"/>
- <xs:element name="categories" type="xs:string"/>
- </xs:sequence>
- </xs:complexType>
- </xs:schema>
- <?xml version="1.0" encoding="UTF-8"?>
- <destination xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="destination.xsd">
- <name>ppp</name>
- <destinationID>PLP</destinationID>
- <shortDescription>shortDescription</shortDescription>
- <longDescription>longDescription</longDescription>
- <typeCode>ZERO</typeCode>
- <categories>categories</categories>
- </destination>
Java Code to validate XML file
- SAXSource source = new SAXSource(new InputSource(xmlFileLocation));
- SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- Schema schema = sf.newSchema(new File("src/validate/blog/customer.xsd"));
- Validator validator = schema.newValidator();
- validator.setErrorHandler(new MyErrorHandler());
- validator.validate(source);