Tutorial

How to validate XML against XSD in Java

Published on August 3, 2022
Default avatar

By Pankaj

How to validate XML against XSD in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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

Validate XML against XSD

Validate XML against XSD java, java xml validation, xsd validator java Here are the sample XSD and XML files used. Employee.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="https://www.w3.org/2001/XMLSchema" 
targetNamespace="https://www.journaldev.com/Employee" 
xmlns:empns="https://www.journaldev.com/Employee" elementFormDefault="qualified">

	<element name="empRequest" type="empns:empRequest"></element>
	
	<element name="empResponse" type="empns:empResponse"></element>

	<complexType name="empRequest">
		<sequence>
			<element name="id" type="int"></element>
		</sequence>
	</complexType>
	
	<complexType name="empResponse">
		<sequence>
			<element name="id" type="int"></element>
			<element name="role" type="string"></element>
			<element name="fullName" type="string"></element>
		</sequence>
	</complexType>
</schema>

Notice that above XSD contains two root element and namespace also, I have created two sample XML file from XSD using Eclipse. EmployeeRequest.xml

<?xml version="1.0" encoding="UTF-8"?>
<empns:empRequest xmlns:empns="https://www.journaldev.com/Employee" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.journaldev.com/Employee Employee.xsd ">
  <empns:id>5</empns:id>
</empns:empRequest>

EmployeeResponse.xml

<?xml version="1.0" encoding="UTF-8"?>
<empns:empResponse xmlns:empns="https://www.journaldev.com/Employee" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.journaldev.com/Employee Employee.xsd ">
  <empns:id>1</empns:id>
  <empns:role>Developer</empns:role>
  <empns:fullName>Pankaj Kumar</empns:fullName>
</empns:empResponse>

Here is another XML file that doesn’t confirms to the Employee.xsd. employee.xml

<?xml version="1.0"?>
<Employee>
	<name>Pankaj</name>
	<age>29</age>
	<role>Java Developer</role>
	<gender>Male</gender>
</Employee>

Here is the program that is used to validate all three XML files against the XSD. The validateXMLSchema method takes XSD and XML file as argument and return true if validation is successful or else returns false. XMLValidation.java

package com.journaldev.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

public class XMLValidation {

    public static void main(String[] args) {
        
      System.out.println("EmployeeRequest.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeRequest.xml"));
      System.out.println("EmployeeResponse.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeResponse.xml"));
      System.out.println("employee.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "employee.xml"));
      
      }
    
    public static boolean validateXMLSchema(String xsdPath, String xmlPath){
        
        try {
            SchemaFactory factory = 
                    SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(new File(xsdPath));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new File(xmlPath)));
        } catch (IOException | SAXException e) {
            System.out.println("Exception: "+e.getMessage());
            return false;
        }
        return true;
    }
}

Output of the above program is:

EmployeeRequest.xml validates against Employee.xsd? true
EmployeeResponse.xml validates against Employee.xsd? true
Exception: cvc-elt.1: Cannot find the declaration of element 'Employee'.
employee.xml validates against Employee.xsd? false

The benefit of using Java XML validation API is that we don’t need to parse the file and there is no third party APIs used.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 24, 2019

very good article. thanks

- afsarnamak

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 21, 2018

    Hello Pankaj, This is really a good example, but the problem is the source passed to validator becomes locked. Delete operation on same file fails with exception. Could you please suggest a way out?

    - Goutam Bhattacharya

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 19, 2018

      Is there any validation for Datamatrix string content. I mean is there a standard combined validation with two pass? In the first pass is the decoding of Datamatrix content 2nd pass: is a schema validation .

      - Tóth Mihály

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 12, 2018

        How can I validate the XML file if the schemaLocation is provided in the file tags. Thanks in advance.

        - Sai

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 24, 2017

          This validation works fine field by field in top down approach like field1 comes first and field2 next,if both fields are invalid as per XSD then error will be thrown for only field1. I really appreciate if u can share how to validate whole XML against XSD in one shot so that all the errors will be thrown in a single response.

          - vinay

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 29, 2016

            what changes to make in the xsd so that the Employee.xml is valid

            - Kannan.S

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              September 25, 2015

              Hi all, Please help me with this following scenario 1 multilevel XSD(parent child) with 1 XML Please give me example… Thanks in Advance

              - ss

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 27, 2015

                Hi Pankaj, I am having a situation where I will get some data from a Stream at run time and I need to convert it into XML by performing some general validations. I am not having any xsd ot xslt. Can you provide some pointers on the same. Thanks, Himanshu

                - Himanshu

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 29, 2015

                  Hi, I’m stuck here: SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Exception Ljava/lang/ExceptionInInitializerError; thrown while initializing Lorg/apache/xerces/impl/xs/SchemaGrammar; Exception Ljava/lang/ExceptionInInitializerError; thrown while initializing Lorg/apache/xerces/impl/xs/XSConstraints; java.lang.IllegalArgumentException: https://www.w3.org/2001/XMLSchema Can you help me please? I’m using Android Studio 1.2.2, jdk 1.8, android 4.4.2 https://stackoverflow.com/questions/31075984/android-xml-validation-using-xsd-both-xerces-and-schemafactory-error

                  - MAI

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 15, 2015

                    How to create the xsd in the first place. Any tools (or Eclipse menu option)available to create the xsd from xml? Thank you Suresh Kumar

                    - Suresh

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel