Skip to main content
Software View

Main navigation

  • Home
  • Trainer Profile
  • Blog
  • Contact
User account menu
  • Log in

Breadcrumb

  1. Home
  2. Blog

Validating an XML document against a given XML Schema in Java

By Kamal Wickramanayake, 9 July, 2010

Many XML validators exist. Here's how you may implement an XML validator in Java. At times you may need to take a programmatic approach like this.

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
/*
 * This is an XML Schema validator written in Java.
 *
 * The implementation is sketched at
 * http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM8.html
 *
 * Improvements required to the code to validate XML files with
 * multiple namespaces are also found at the above URL.
 *
 */
public class XMLSchemaValidator {
 
    static final String JAXP_SCHEMA_LANGUAGE
            = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    static final String W3C_XML_SCHEMA 
            = "http://www.w3.org/2001/XMLSchema";
    static final String JAXP_SCHEMA_SOURCE
            = "http://java.sun.com/xml/jaxp/properties/schemaSource";
     
    public static void main(String[] args) {
        if(args.length != 2) {
            System.err.println(
                    "Usage: java XMLSchemaValidator schemafile.xsd xmlfile.xml");
            System.exit(1);
        }
         
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
         
        factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);

        // Set the schema file
        factory.setAttribute(JAXP_SCHEMA_SOURCE, new File(args[0]));
         
        try {
            DocumentBuilder parser = factory.newDocumentBuilder();

            // Parse the file. If errors found, they will be printed.
            parser.parse(args[1]);
             
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

What we do here is simply parsing an XML document. To do so, we create a DocumentBuilderFactory. We request the DocumentBuilderFactory to validate a given XML document against a given XML Schema document by invoking the setValidate() method of the factory. Just before we start parsing the XML document, we specify the XML Schema file by using the setAttribute(JAXP_SCHEMA_SOURCE,...) of the factory. Then we create a DocumentBuilder from the factory and invoke the parse() method of it. If the XML document is invalid, the catch block prints the details.

You can save the above in a file called XMLSchemaValidator.java. Compile it as follows:

javac XMLSchemaValidator.java

Validate an XML file against an XML Schema file as follows:

java XMLSchemaValidator myschema.xsd myxmldoc.xml
Java
Web Services
XML
  • Add new comment

Highlights

  • O'Reilly Book "97 Things Every Software Architect Should Know" Accepts A Write Up From Kamal
  • "Service Oriented Architecture - Making IT Infrastructure Speaks Business" - Presentation At The ISACA 4th Annual Conference
  • The Second Bacth Of ICTA Nanasala e-Society Members Receives Trainings On HTML/CSS and GIMP
  • GIMP Training For ICTA Nanasala Project
  • Agile Processes Training For PPSL (Pvt) Ltd
  • Computer Society of Sri Lanka (CSSL) - Talk on "Introduction to IT Governance and Enterprise Architecture"
  • Motorola Sends A Second Batch Through Software Patterns Training
  • Kamal To Act As The Marketing Director - ISACA Sri Lanka Chapter
  • ISACA Sri Lanka Chapter Invites Kamal To Join As A Board Member
  • Epic Lanka Technologies (Pvt) Ltd Receives Java SE And Java EE Trainings From Software View
  • Patterns Training For PPSL (Pvt) Ltd
  • ISACA Members Day Presentation On "Introduction To IT Governance And Enterprise Architecture"
  • Opening Lecture On Information Technology For SLIDA Master Of Public Management Course Delivered By Kamal
  • Customized Java Enterprise Edition Training For SLIDA
  • No One To Beat Software View - Epic Lanka Technologies (Pvt) Ltd
  • Motorola Receives Software Patterns Training From Software View
  • Custom Java Enterprise Edition Training for ICTA/SLIDA - Only from Software View!
  • Java EE 5, JavaServer Faces, Hibernate And Spring For PPSL (Pvt) Ltd
  • "Brain Trust" For Linux Journal Weekly Newsletter From Kamal
  • Java Platform, Enterprise Edition 5 Training At The CEIT, University Of Peradeniya
  • Another Group Of Around 100 Sri Lanka Telecom Engineers And Managers Were Service Oriented!
  • Java Platform, Enterprise Edition 5 Training Will Be Held At The CEIT, University Of Peradeniya
  • Service Oriented Architecture: Another Two Sessions Conducted at SLT
  • Photos of IET Monthly Forum at the Peradeniya University
RSS feed
Copyright © 2007 - 2023 Software View