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:schema
    targetNamespace="http://schemas.xmlbeam.org/tutorials/18"
    elementFormDefault="qualified">
     
    <xs:complexType name="VegetablesType">
        <xs:sequence>
            <xs:element name="Vegetable" type="VegetableType" minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
    </xs:complexType>
     
    <xs:complexType name="VegetableType">
        <xs:attribute name="name" type="xs:string" use="required" />
        <xs:attribute name="color" type="xs:string" default="green" />
    </xs:complexType>
 
    <xs:element name="Vegetables" type="VegetablesType" />
</xs:schema>
<?xml version='1.0' encoding='UTF-8' ?>
    <Vegetable name="Tomato" color="red" />
    <Vegetable name="Cucumber" />
</Vegetables>

Projection

public interface Vegetable {
    @XBRead("@name")
    String getName();
 
    @XBRead("@color")
    String getColor();
}
public interface Vegetables {
    @XBRead("/xbdefaultns:Vegetables/xbdefaultns:Vegetable[@name='{0}']")
    Vegetable getVegetable(String name);
}

Example Code

public class TestSchemaHandling extends TutorialTestCase {
 
    Vegetables vegetables;
 
    @Before
    public void readVegetables() throws Exception {
        XBProjector projector = new XBProjector(new DefaultXMLFactoriesConfig(){
 
            private static final long serialVersionUID = 1L;
 
            @Override
            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"));
                    factory.setSchema(schema);
                } catch (SAXException e) {
                    throw new RuntimeException("Error loading schema", e);
                }
                return factory;
            }
        });
 
        vegetables = projector.io().fromURLAnnotation(Vegetables.class);
    }
 
    @Test
    public void testReadActualValue() {
        assertEquals("red", vegetables.getVegetable("Tomato").getColor());
    }
 
    @Test
    public void testReadDefaultValueDefinedInSchema() {
        assertEquals("green", vegetables.getVegetable("Cucumber").getColor());
    }
}