是否可以从带注释的JAXB类生成XSD?

Naf*_*Kay 45 java xsd jaxb

我已经编写了许多使用JAXB进行序列化的类,我想知道是否有办法根据注释为每个对象生成一个XSD文件.有这个工具吗?

类似的东西generate-xsd com/my/package/model/Unit.java很棒.有没有做到这一点?

bdo*_*han 73

是的,您可以generateSchema在JAXBContext上使用该方法:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
SchemaOutputResolver sor = new MySchemaOutputResolver();
jaxbContext.generateSchema(sor);
Run Code Online (Sandbox Code Playgroud)

您可以利用实现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;
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 另外,请参阅 Maven 插件:http://stackoverflow.com/questions/7251458/generating-xsd-schemas-from-jaxb-types-in-maven (2认同)
  • 它是由在其中一个JAXB注释类上实现接口引起的.这很奇怪,因为接口只包含一个方法(一个getter),它与JAXB属性无关. - **所以这个例子非常好,不需要额外的魔法**,但是模式生成器比编组器更挑剔. (2认同)
  • 我认为最好使用`result.setSystemId(file.getAbsolutePath());`而不是`result.setSystemId(file.toURI().toURL().toString());`我有一个文件没有使用时发现异常. (2认同)