How do I validate XML against XSD in Java?

The javax.xml.validation package provides an API for XML documents validation. The validation process verify that an XML document is an instance of a specified XML schema file or XSD file. In this example we are going to validate if the records.xml file below ins an instance of the records.xsd schema. First we will create the following XML file and an XSD file it should follow.

The XML file:

<?xml version="1.0" encoding="UTF-8"?>
            <title>Brand New Eyes</title>
            <genre>Punk Rock</genre>
            <artist>Various Artist</artist>

The XSD file:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="" attributeFormDefault="unqualified"
    <xs:element name="root" type="rootType">

    <xs:complexType name="rootType">
            <xs:element name="records" type="recordsType"/>

    <xs:complexType name="recordsType">
            <xs:element name="record" type="recordType" maxOccurs="unbounded" minOccurs="0"/>

    <xs:complexType name="recordType">
            <xs:element type="xs:string" name="title"/>
            <xs:element type="xs:string" name="artist"/>
            <xs:element type="xs:string" name="genre"/>
            <xs:element type="xs:short" name="year"/>

The code snippet below will handle the validation process in the following steps. In the main() method we create the XMLValidator instance and call the validate() method and pass the XML file and the XSD file. Our validate() method start by creating an instance of SchemaFactory. The SchemaFactory.newInstance() method return an instance of SchemaFactory. In this example we are create a W3C XML Schema.

The next step is to create a Schema object by calling the schemaFactory.newSchema() and pass the schema / XSD file. The Schema object will allow us the create an instance of javax.xml.validation.Validator by calling the schema.newValidator() method. And finally to validate if the XML is valid we call validator.validate() method and pass the XML file to be validated. If the XML is not valid this validate method will throw exceptions.

The Java code:

package org.kodejava.example.xml;

import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.util.Objects;

public class XMLValidator {
    public static final String XML_FILE = "records.xml";
    public static final String SCHEMA_FILE = "records.xsd";

    public static void main(String[] args) {
        XMLValidator XMLValidator = new XMLValidator();
        boolean valid = XMLValidator.validate(XML_FILE, SCHEMA_FILE);

        System.out.printf("%s validation = %b.", XML_FILE, valid);

    private boolean validate(String xmlFile, String schemaFile) {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            Schema schema = schemaFactory.newSchema(new File(getResource(schemaFile)));

            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new File(getResource(xmlFile))));
            return true;
        } catch (SAXException | IOException e) {
            return false;

    private String getResource(String filename) throws FileNotFoundException {
        URL resource = getClass().getClassLoader().getResource(filename);

        return resource.getFile();

How to generate a wrapper element around XML representation in JAXB?

In this example you’ll learn how to use the JAXB @XmlElementWrapper annotation. This annotation can be use to generate a wrapper element around an XML element representation. When no name defined, the @XmlElementWrapper annotation uses the property name as the wrapper element name. Let’s see the code snippet below.

package org.kodejava.example.jaxb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

public class Record {
    private Integer id;
    private String title;
    private List tracks = new ArrayList<>();

    public Integer getId() {
        return id;

    public void setId(Integer id) { = id;

    public String getTitle() {
        return title;

    public void setTitle(String title) {
        this.title = title;

    @XmlElementWrapper(name = "trackList")
    @XmlElement(name = "track")
    public List getTracks() {
        return tracks;

    public void setTracks(List tracks) {
        this.tracks = tracks;

Below is the code snippet for marshaling the Record object into an XML document. Before the marshalling take place we create an object of Record and adds a some Tracks into it.

package org.kodejava.example.jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBElementWrapper {
    public static void main(String[] args) {
        Track track1 = new Track();
        track1.setTitle("Love Me Do");

        Track track2 = new Track();
        track2.setTitle("From Me To You");

        Track track3 = new Track();
        track3.setTitle("She Loves You");

        Record record = new Record();
        record.setTitle("The Beatles 1");

        try {
            JAXBContext context = JAXBContext.newInstance(Record.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(record, System.out);

            Writer writer = null;
            try {
                writer = new FileWriter("Record.xml");
                marshaller.marshal(record, writer);
            } finally {
                if (writer != null) {
        } catch (JAXBException e) {
        } catch (IOException e) {

The above program will generated the following XML document.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<record id="1">
    <title>The Beatles 1</title>
        <track id="1">
            <title>Love Me Do</title>
        <track id="2">
            <title>From Me To You</title>
        <track id="3">
            <title>She Loves You</title>