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:
<?xml version="1.0" encoding="UTF-8"?><xs:schema 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> |
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);} |
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()); }} |