[英]Is it possible to generate a XSD from a JAXB-annotated class?
我已经使用 JAXB 编写了许多用于序列化的类,我想知道是否有一种方法可以根据注释为这些对象中的每一个生成 XSD 文件。 有这个工具吗?
像generate-xsd com/my/package/model/Unit.java
这样的东西会很棒。 有什么东西可以做到这一点吗?
是的,您可以在 JAXBContext 上使用generateSchema
方法:
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
SchemaOutputResolver sor = new MySchemaOutputResolver();
jaxbContext.generateSchema(sor);
您利用SchemaOutputResolver
的实现来控制输出的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;
}
}
我稍微修改了答案,以便我们可以通过我们的类并获取创建 XSD 文件的path
:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.