Fork me on GitHub

Tutorial 16

E16 Using an XML schema to define default values and validate documents

This example shows how to use a schema with your projections.

This time we read some data from xml files which use a defined schema. This way we can handle default values for attributes and honor restrictions.

The solution to this shows:

  • Usage of a schema for validation xml source.
  • Reading default values specified in a schema works as expected.

XML Data

<?xml version="1.0" encoding="UTF-8"?>
    <xs:complexType name="VegetablesType">
            <xs:element name="Vegetable" type="VegetableType" minOccurs="0" maxOccurs="unbounded" />
    <xs:complexType name="VegetableType">
        <xs:attribute name="name" type="xs:string" use="required" />
        <xs:attribute name="color" type="xs:string" default="green" />
    <xs:element name="Vegetables" type="VegetablesType" />
<?xml version='1.0' encoding='UTF-8' ?>
    <Vegetable name="Tomato" color="red" />
    <Vegetable name="Cucumber" />


public interface Vegetable {
    String getName();
    String getColor();
public interface Vegetables {
    Vegetable getVegetable(String name);

Example Code

public class TestSchemaHandling extends TutorialTestCase {
    Vegetables vegetables;
    public void readVegetables() throws Exception {
        XBProjector projector = new XBProjector(new DefaultXMLFactoriesConfig(){
            private static final long serialVersionUID = 1L;
            public DocumentBuilderFactory createDocumentBuilderFactory() {
                DocumentBuilderFactory factory = super.createDocumentBuilderFactory();
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                try {
                    Schema schema = schemaFactory.newSchema(getClass().getResource("schema.xsd"));
                } catch (SAXException e) {
                    throw new RuntimeException("Error loading schema", e);
                return factory;
        vegetables =;
    public void testReadActualValue() {
        assertEquals("red", vegetables.getVegetable("Tomato").getColor());
    public void testReadDefaultValueDefinedInSchema() {
        assertEquals("green", vegetables.getVegetable("Cucumber").getColor());