【问题标题】:Is it possible to generate a XSD from a JAXB-annotated class?是否可以从带有 JAXB 注释的类生成 XSD?
【发布时间】:2011-08-27 01:52:25
【问题描述】:

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

generate-xsd com/my/package/model/Unit.java 这样的东西会很棒。有什么可以做到这一点吗?

【问题讨论】:

    标签: java xsd jaxb


    【解决方案1】:

    是的,您可以在 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;
        }
    
    }
    

    【讨论】:

    • 另外,请参阅 Maven 插件:stackoverflow.com/questions/7251458/…
    • 嗨,这个方法对我没有任何作用(createOutput 从未调用过)。我正在使用这个实现:com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl。有什么想法吗? - 谢谢
    • 是的,尝试了断点和 System.err.print。我正在使用 jaxb.index 文件从包名称创建上下文。否则我的上下文效果很好(它可以毫无问题地编组对象图)。
    • 这是由在 JAXB 注释类之一上实现接口引起的。这很奇怪,因为接口只包含一个方法(getter),并且与 JAXB 属性无关。 - 所以这个例子非常好,不需要额外的魔法,但是模式生成器比编组器要挑剔得多。
    • 我认为使用result.setSystemId(file.getAbsolutePath());而不是result.setSystemId(file.toURI().toURL().toString());会更好我使用它时遇到了一个文件未找到异常。
    【解决方案2】:

    我稍微修改了答案,这样我们就可以通过我们的课程并获得创建 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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      相关资源
      最近更新 更多