Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

How you can validate your XML file in Java





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

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">  
  3.   <xs:element name="destination" type="Destination"/>  
  4.   <xs:complexType name="Destination">  
  5.     <xs:sequence>  
  6.       <xs:element name="name" type="xs:string"/>  
  7.       <xs:element name="destinationID" type="xs:string" minOccurs="0"/>  
  8.       <xs:element name="shortDescription" type="xs:string" minOccurs="0"/>  
  9.       <xs:element name="longDescription" type="xs:string" minOccurs="0"/>  
  10.       <xs:element name="stateID" type="xs:string"/>  
  11.       <xs:element name="typeCode" type="xs:int"/>  
  12.       <xs:element name="countryCode" type="xs:string"/>  
  13.       <xs:element name="categories" type="xs:string"/>  
  14.     </xs:sequence>  
  15.   </xs:complexType>  
  16. </xs:schema> 
My XML file

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <destination xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="destination.xsd">  
  3.     <name>ppp</name>  
  4.   <destinationID>PLP</destinationID>  
  5.   <shortDescription>shortDescription</shortDescription>  
  6.   <longDescription>longDescription</longDescription>  
  7.   <typeCode>ZERO</typeCode>  
  8.   <categories>categories</categories>  
  9. </destination> 
 Java Code to validate XML file


  1. SAXSource source = new SAXSource(new InputSource(xmlFileLocation));  
  2. SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);  
  3.  Schema schema = sf.newSchema(new File("src/validate/blog/customer.xsd"));  
  4.  Validator validator = schema.newValidator();  
  5. validator.setErrorHandler(new MyErrorHandler());  
  6.  validator.validate(source);