Tutorial

How to validate XML against XSD in Java

Published on August 3, 2022
author

Pankaj

How to validate XML against XSD in Java

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 our products

About the author(s)

Category:
Tutorial
Tags:

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 18, 2013

Very good and Simple solution Pankaj. Keep Going

- Rajesh Kumar Yuvaraj

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 7, 2014

Is it possible to identify all the invalid xml tags in one go?

- Phanendra Akurathi]

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 7, 2014

Simple and sweet. Thanks

- Srinivas

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 4, 2014

    Short and clear. Thanks a lot for this good start-up example.

    - Darko

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 12, 2014

      Hi, this worked wonderfull. but i have a little change, what if i have the XML and XSD files, into strings? lets say a string read from the database, with the xml , xsd information, String xml =“”; String xsd =“”; then validateXMLSchema(xsd,xml) How do i convert the “new File” to accept the String with the data? or, do convert the “newSchema” and “validator.validate” to accept the String with the data? Schema schema = factory.newSchema(new File(xsdPath)); validator.validate(new StreamSource(new File(xmlPath))); thanks!!

      - Mintakastar

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 18, 2014

        Hi plese provide the code for the same above mentioned but not single its multiple xsd. So my requirement is How to Validate XML with multiple XSD Schemas.it is very urgent requirement in my project.So please give the code.And one xsd is included in other xsd and so on.So I want to validate this xml file against the multiple schemas. Regards Krishanveni

        - krishanveni

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          August 11, 2014

          Very good article and easy to use also…

          - Sathish Gollapally

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 21, 2014

            Just what I was looking for, thanks!

            - Brandon

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 8, 2015

              That’s what I was looking for. Thanks for sharing.

              - Bhavesh

                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!

                  Become a contributor for community

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

                  DigitalOcean Documentation

                  Full documentation for every DigitalOcean product.

                  Resources for startups and SMBs

                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                  Get our newsletter

                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                  New accounts only. By submitting your email you agree to our Privacy Policy

                  The developer cloud

                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                  Get started for free

                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                  *This promotional offer applies to new accounts only.