简体   繁体   中英

Is it possible to generate a XSD from a JAXB-annotated class?

I've written a number of classes using JAXB for serialization and I was wondering if there was a way to generate a XSD file for each of these objects based on the annotations. Is there a tool for this?

Something like generate-xsd com/my/package/model/Unit.java would be awesome . Does anything exist to do this?

Yes, you can use the generateSchema method on JAXBContext:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
SchemaOutputResolver sor = new MySchemaOutputResolver();
jaxbContext.generateSchema(sor);

You leverage an implementation of SchemaOutputResolver to control where the output goes:

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;
    }

}

I have modified the answer a bit so we can pass our class and also get the path where XSD file has been created:

public class SchemaGenerator {
    public static void main(String[] args) throws JAXBException, IOException {
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        SchemaOutputResolver sor = new MySchemaOutputResolver();
        jaxbContext.generateSchema(sor);
    }
}

class MySchemaOutputResolver extends SchemaOutputResolver {
    @SneakyThrows
    public Result createOutput(String namespaceURI, String suggestedFileName) {
        File file = new File(suggestedFileName);
        StreamResult result = new StreamResult(file);
        result.setSystemId(file.getAbsolutePath());
        System.out.println(file.getAbsolutePath());
        return result;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM