Skip to content

Instantly share code, notes, and snippets.

@d3ep4k
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d3ep4k/19fbf50f28993a0af087 to your computer and use it in GitHub Desktop.
Save d3ep4k/19fbf50f28993a0af087 to your computer and use it in GitHub Desktop.
Java XML Validation using XSD
<?xml version="1.0"?>
<emp>
<name>apple</name>
<age>60</age>
<salary>10</salary>
</emp>
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:simpleType name="name">
<xs:restriction base="xs:string">
<xs:maxLength value="10" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="age">
<xs:restriction base="xs:integer">
<xs:maxInclusive value="60" />
<xs:minInclusive value="20" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="salary">
<xs:restriction base="xs:integer">
<xs:maxInclusive value="100000" />
<xs:minInclusive value="20000" />
</xs:restriction>
</xs:simpleType>
<xs:element name="emp">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="name"/>
<xs:element name="age" type="age"/>
<xs:element name="salary" type="salary"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
import javax.xml.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.validation.*;
import java.io.*;
import java.net.*;
import org.xml.sax.*;
public class XSDValidation{
public static void main(String[] args) throws Exception{
Source xmlFile = new StreamSource(new File(args[0]));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File(args[1]));
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment