Margus
Margus

Reputation: 20058

Suitable XML schema for Marshaller setSchema

I'm having a hard time figuring out the correct schema (to validate the structure and data types) of simple classes. For example, I could get answer for Employee class with schemagen (supplied with JDK), but still could not get it to work for HumanResources.

I'm trying to serialize collection of Employee class instances to XML. For that, I have created class HumanResources, that contains a list of Employee class elements. Example:

    ArrayList<Employee> ems = getTestData();
    HumanResources hm = new HumanResources(ems);
    SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
    JAXBContext jaxbContext = JAXBContext.newInstance(HumanResources.class);

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setSchema(sf.newSchema(new File("src\\server\\HumanResources.xsd")));
    marshaller.marshal( new JAXBElement<HumanResources>(
            new QName(null, "HumanResources"), HumanResources.class, hm), os);

Upvotes: 2

Views: 3808

Answers (1)

bdoughan
bdoughan

Reputation: 149047

Below is an example of how to create an XML schema using the JAXBContext:

First you must create a class that extends javax.xml.bind.SchemaOutputResolver.

public class MySchemaOutputResolver extends SchemaOutputResolver {

    public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
        File file = new File(suggestedFileName);
        StreamResult result = new StreamResult(file);
        result.setSystemId(file.toURI().toURL().toString());
        return result;
    }

}

Then use an instance of this class with JAXBContext to capture the generated XML Schema.

Class[] classes = new Class[4]; 
classes[0] = org.example.customer_example.AddressType.class; 
classes[1] = org.example.customer_example.ContactInfo.class; 
classes[2] = org.example.customer_example.CustomerType.class; 
classes[3] = org.example.customer_example.PhoneNumber.class; 
JAXBContext jaxbContext = JAXBContext.newInstance(classes);

SchemaOutputResolver sor = new MySchemaOutputResolver();
jaxbContext.generateSchema(sor);

For more information see:

Upvotes: 2

Related Questions