[英]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.