Create XSD file with JAXB

This post is a sequel of the two previous ones talking about serializing Java classes to XML through JAXB in Eclipse. So, it started when I wanted to serialize objects without using an XSD schema… and the only solution I found was by creating the ObjectFactory.java class that JAXB needs when going through marshalling process (check More on XML serialization with JAXB post).

Still, this solution was not good enough for me, I wanted to find a mechanism inside JAXB to do the task, not outside it, or by cheating… So I googled some more and found a way to generate an XML schema (XSD file) from Java classes; not what I was looking for, but interesting (and tricky) stuff. In order to do this, add to your Java project (described in previous 2 articles) the following method:

public void generateSchema(String suggestedSchemaName) throws Exception
{
    final File parentFolder = new File(".");
    final String schemaName = suggestedSchemaName;
        
    JAXBContext jc = JAXBContext.newInstance(Graph.class);
    jc.generateSchema(new SchemaOutputResolver() {
        @Override
        public Result createOutput(String namespace, String schema) throws IOException {
            return new StreamResult(new File(parentFolder, schemaName));
        }
    });
}

As you can see, JAXBContext class has the generateSchema method, which takes an instance of a SchemaOutputResolver class, that needs to override the createOutput method in order to output the XSD file. So you can afterwards call the method presented above as follow:

generateSchema(“graphXmlSchema.xsd”);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: