PIZZADOMU.INFO

Minutes straight against java xsd xml validating big

Java XML Validation API can be used to validate XML against an XSD. javax.xml.validation.Validator class is used in this program to validate xml file against xsd file.

Here is the Sample XML file:

<?xml version="1.0"?> <employee> <personalinformation> <firstname>Anil Krmar</firstname> <lastname>Anil Krmar</lastname> <dateofbirth>Anil Krmar</dateofbirth> <email>Anil Krmar</email> <telephone>9989762143</telephone> </personalinformation> <workdetails> <company>i3-software</company> <department>i3-software</department> <designation>i3-software</designation> <email>i3-software</email> <telephone>9989762143</telephone> </workdetails> <address> <personaladdress> <huseno>1-90/B</huseno> <street>KPHB COLONY</street> <city>KUKATPALLY</city> <state>AP</state> <postalcode>500072</postalcode> </personaladdress> <workaddress> <huseno>1-90/B</huseno> <street>KPHB COLONY</street> <city>KUKATPALLY</city> <state>AP</state> <postalcode>500072</postalcode> </workaddress> </address> </employee>

Next step is to create the XSD from the XML file.
We can create XSD from XML throug online. Please click here to generate XSDbform XML.

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="employee"> <xs:complexType> <xs:sequence> <xs:element name="personalinformation"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="firstname"/> <xs:element type="xs:string" name="lastname"/> <xs:element type="xs:string" name="dateofbirth"/> <xs:element type="xs:string" name="email"/> <xs:element type="xs:long" name="telephone"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="workdetails"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="company"/> <xs:element type="xs:string" name="department"/> <xs:element type="xs:string" name="designation"/> <xs:element type="xs:string" name="email"/> <xs:element type="xs:long" name="telephone"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="address"> <xs:complexType> <xs:sequence> <xs:element name="personaladdress"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="huseno"/> <xs:element type="xs:string" name="street"/> <xs:element type="xs:string" name="city"/> <xs:element type="xs:string" name="state"/> <xs:element type="xs:int" name="postalcode"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="workaddress"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="huseno"/> <xs:element type="xs:string" name="street"/> <xs:element type="xs:string" name="city"/> <xs:element type="xs:string" name="state"/> <xs:element type="xs:int" name="postalcode"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

Here is the program that is used to validate XML file against the XSD. The validateXMLSchema method takes XSD and XML String as argument and return “document is valid” if validation is successful or else returns “document is not valid”.

package com.codesuggestions.xml; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.apache.log4j.Logger; import org.xml.sax.SAXException; public class XMLValidator { private static final Logger logger = Logger.getLogger(XMLValidator.class); public static void main(String[] args) { try { String xml = readFileAsString("C:\\emp.xml"); String xsd = readFileAsString("C:\\emp.xsd"); System.out.println("" + xml); String response = validate(xml, xsd); System.out.println("Employee.xml validates against Employee.xsd? " + response); } catch (Exception ex) { java.util.logging.Logger.getLogger(XMLValidator.class.getName()).log(Level.SEVERE, null, ex); } /** * @param filePath the name of the file to open. Not sure if it can accept * URLs or just filenames. Path handling could be better, and buffer sizes * are hardcoded */ private static String readFileAsString(String filePath) throws java.io.IOException { StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = new BufferedReader(new FileReader(filePath)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); return fileData.toString(); } /** * * @param xml * @param xsd * @return */ public static String validate(String xml, String xsd) throws SAXException, IOException { boolean isValid = false; String errorMessage = null; // 1. Lookup a factory for the W3C XML Schema language SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); /** * 2. Compile the schema. Here the schema is loaded from a * javax.xml.transform.Source, but you could use a java.net.URL or a * java.io.File instead. */ Schema schema = factory.newSchema(new StreamSource(new StringReader(xsd))); // 3. Get a validator from the schema. Validator validator = schema.newValidator(); // 4. Parse the document you want to check. Source source = new StreamSource(new StringReader(xml)); // 5. Check the document try { validator.validate(source); isValid = true; } catch (SAXException e) { errorMessage = e.toString(); logger.error("SAXException Occured in validate(String , String)::" + e.getMessage()); } if (isValid == true) { errorMessage = "Document is valid!"; } return (errorMessage == null) ? "" : errorMessage; } }

Output of the above program is:

Employee.xml validates against Employee.xsd? Document is valid!

Java, XML

http://www.codesuggestions.com/java/how-to-validate-xml-against-xsd-in-java/