JAXB marshal schema validation

In a How to validate XML versus XSD in Java tutorial shows you how to validate an validate xml vs xsd file using the javax.xml.validation APIs. In this tutorial shows you how to use JAXB marshal schema validation during marshal operation. Here is a way to leverage the JAXB APIs.

Such as the previous tutorial, you should define Fruit XML schema Fruit.xsd

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="fruit">

<xs:complexType>

<xs:sequence>

<xs:element name="id"type="xs:int"></xs:element>

<xs:element name="name"type="NameFruit"></xs:element>

<xs:element name="produceby"type="ProduceBy"minOccurs="0"/>

</xs:sequence>

</xs:complexType>

</xs:element>

<xs:simpleType name="NameFruit">

<xs:restriction base="xs:string">

<xs:maxLength value="10"/>

</xs:restriction>

</xs:simpleType>

<xs:simpleType name="ProduceBy">

<xs:restriction base="xs:string">

<xs:whiteSpace value="collapse"/>

<xs:maxLength value="250"/>

</xs:restriction>

</xs:simpleType>

</xs:schema>

Here, you should use a java model that may be generated by JAXB in Eclipse such as the below figure (you could define manually this model by yourself)

JAXB marshal schema validation

then you get java file

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

packagecom.javabycode.xml;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)

@XmlType(name="",propOrder={"id","name","produceby"})

@XmlRootElement(name="fruit")

publicclassFruit{

protectedintid;

@XmlElement(required=true)

protectedStringname;

protectedStringproduceby;

publicintgetId(){

returnid;

}

publicvoidsetId(intvalue){

this.id=value;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringvalue){

this.name=value;

}

publicStringgetProduceby(){

returnproduceby;

}

publicvoidsetProduceby(Stringvalue){

this.produceby=value;

}

}

Customize the JAXB ValidationEventHandler

ValidationEventHandler catches all events that JAXB reports after finished validation. The event is an instance of ValidationEvent, and provides many details about the validation issue. You could get these details also by using SAXParseException. Here, the CustomValidationEventHandler will get information of all events and print the formatted messages.