Validate XML File with SAX

Create new package named data. In this package, create new xml file named account.xml as below:

<?xml version="1.0" encoding="UTF-8"?>

<account>
	<username>acc1</username>
	<fullName>
		<firstName>PMK</firstName>
		<lastName>Lab</lastName>
	</fullName>
	<age>29</age>
</account>

In data package, create new xsd file named account.xsd as below:

<?xml version="1.0"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
	elementFormDefault="qualified">

	<xs:element name="account">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="username" type="typeUsername"></xs:element>
				<xs:element name="fullName" type="typeFullName"></xs:element>
				<xs:element name="age" type="typeAge"></xs:element>
			</xs:sequence>
		</xs:complexType>
	</xs:element>

	<xs:simpleType name="typeUsername">
		<xs:restriction base="xs:string">
			<xs:minLength value="3"></xs:minLength>
			<xs:maxLength value="10"></xs:maxLength>
		</xs:restriction>
	</xs:simpleType>

	<xs:complexType name="typeFullName">
		<xs:sequence>
			<xs:element name="firstName" type="xs:string"></xs:element>
			<xs:element name="lastName" type="xs:string"></xs:element>
		</xs:sequence>
	</xs:complexType>

	<xs:simpleType name="typeAge">
		<xs:restriction base="xs:int">
			<xs:minInclusive value="18"></xs:minInclusive>
			<xs:maxInclusive value="120"></xs:maxInclusive>
		</xs:restriction>
	</xs:simpleType>

</xs:schema>




Create new package, named demo. In this package, create new java class, named Main as below

package demo;

import java.io.File;
import java.io.FileReader;
import javax.xml.XMLConstants;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.InputSource;

public class Main {

	private static boolean isValid(String xmlFile, String xsdFile) {
		boolean result = true;
		try {
			SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			Schema schema = schemaFactory.newSchema(new File(xsdFile));
			Validator validator = schema.newValidator();
			validator.validate(new SAXSource(new InputSource(new FileReader(xmlFile))));
		} catch (Exception e) {
			result = false;
		}
		return result;
	}

	public static void main(String[] args) {

		String xmlFile = "src\\data\\account.xml";
		String xsdFile = "src\\data\\account.xsd";
		System.out.println("Result: " + isValid(xmlFile, xsdFile));

	}

}
Result: true