我已经使用JAXB编写了许多用于序列化的类,我想知道是否有一种方法可以根据注释为每个对象生成XSD文件。有这个工具吗?
像generate-xsd com/my/package/model/Unit.java
这样的东西会很棒。有没有做到这一点?
答案 0 :(得分:71)
是的,您可以在JAXBContext上使用generateSchema
方法:
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
SchemaOutputResolver sor = new MySchemaOutputResolver();
jaxbContext.generateSchema(sor);
您利用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;
}
}
答案 1 :(得分:0)
我稍微修改了答案,以便我们可以通过我们的类并获得创建 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;
}
}