【问题标题】:How to use an XML Schema to validate @ResponseBody marshalled by JAXB如何使用 XML Schema 验证由 JAXB 编组的 @ResponseBody
【发布时间】:2012-03-22 15:00:06
【问题描述】:

我有一个使用 @ResponseBody 和 @XmlElement 编组 (JAXB) 返回大量 XML 的系统。

使用创建的 Schema 验证生成的 XML 的最佳方法是什么?

我仍然需要遍历元素并测试它们,但是 XML Schema 验证将使第二部分变得非常容易。

【问题讨论】:

    标签: spring unit-testing spring-mvc integration-testing


    【解决方案1】:

    Spring 让这一切变得简单(假设您使用 Jaxb2Marshaller):

    <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
      <property name="schema" value="file:/some/path/schema.xsd"/>
    </bean>
    

    【讨论】:

    • 我对 Spring 很陌生,但是我如何指定哪个 xsd 到哪个 @ResponseBody 这是我需要测试的(控制器返回基于组合模型的编组 XML)
    • Oki,我添加了&lt;bean id="marshaller" class="test.project.util.ClasspathScanningJaxb2Marshaller"&gt;&lt;property name="schema" value="classpath:service.xsd" /&gt;&lt;property name="basePackages" value="test.project" /&gt;&lt;/bean&gt;,而不是添加classesToBeBound,我使用了walgemoed.org/2010/12/jaxb2-spring-ws。但是,一切运行良好,从某种意义上说,即使是无效的 xsd 也不会给出任何错误消息
    • 查看 ibm.com/developerworks/web/library/wa-restful(清单 4)以获取如何设置 http 编组转换器并为其提供上述编组器的示例。
    • 嗯...我去看看。谢谢
    【解决方案2】:

    为 JAXB 编组器和解组器设置 XSD 架构:

    SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    InputStream schemaStream = openMySchemaFileStream();
    Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));    
    marshaller.setSchema(schema);
    unmarshaller.setSchema(schema);
    

    通过解组验证 XML 字符串:

    Reader reader = new StringReader(xml);
    StreamSource source = new StreamSource(reader);
    unmarshaller.unmarshal(source, YourJAXBClass.class);
    

    通过编组到 SAX 的 DefaultHandler 来验证 JAXB 对象,它什么都不做:

    marshaller.marshal(obj, new DefaultHandler());
    

    【讨论】:

    • 嗯,我如何将它连接到 Spring 以及 @ResponseBody 中的结果?
    猜你喜欢
    • 1970-01-01
    • 2011-01-30
    • 2011-01-29
    • 2011-06-19
    • 1970-01-01
    • 2018-04-10
    • 2014-02-27
    • 2016-02-03
    相关资源
    最近更新 更多