【问题标题】:Validating an xml against xsd that was used to generate Beans针对用于生成 Bean 的 xsd 验证 xml
【发布时间】:2014-11-19 13:00:45
【问题描述】:

我通过 ant-build 从几个 xsd 生成了一些 bean。

在解组 xml 时,我想验证那个。据我所知,现在有办法用豆子自己做到这一点,必须做这样的事情:

JAXBContext context = JAXBContext.newInstance(Bean.class);
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("whatever.xsd"));

Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setSchema(schema);
unmarshaller.setEventHandler(validationHandler);

return (Bean) unmarshaller.unmarshal(givenXmlString);

我的问题是new File("whatever.xsd")。我不想硬编码 xsd 的 URL,这可能会在以后更改(即通过重构项目)并且会在运行时中断,因为人们忘记(或不知道)更改该 URL。

想法:
我唯一的想法是将 xsd 复制到与生成的 bean 相同的文件夹中,并使用一个 bean 的包名在运行时生成 url。

有更好的想法吗?

【问题讨论】:

  • 能否将所有涉及到的 xsd 放入外部 properties 进行验证。
  • @Xstian:你是说将 xsds 的 url 放在属性文件中吗?我更新了我的帖子以解释为什么这无济于事:我不想硬编码 xsd 的 URL,这可能会在以后更改(即通过重构项目)并且会在运行时中断,因为有人忘记了(或不知道)来改变那个网址。
  • 您可以使用一些硬编码的默认值并通过外部属性文件对其进行自定义。

标签: java xml validation xsd


【解决方案1】:

您可以将sf.newSchema(Source[])javax.xml.transform.Source 实现之一一起使用,而不是sf.newSchema(File),例如javax.xml.transform.stream.StreamSource.

【讨论】:

    猜你喜欢
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    相关资源
    最近更新 更多