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 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() {
        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:


%d bloggers like this: