2012-03-22 40 views
3

我有一個系統使用@ResponseBody和@XmlElement編組(JAXB)返回了很多XML。如何使用XML模式來驗證由JAXB編組的@ResponseBody

使用創建的Schema驗證生成的XML的最佳方法是什麼?

我仍然需要遍歷元素並測試它們,但是使用XML Schema驗證會使第二部分非常容易。對於JAXB編組與解組

+0

您是否找到解決方案? – 2015-06-05 08:53:03

+0

不幸的是沒有。 – mamruoc 2015-06-06 21:40:49

回答

1

設置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()); 
+0

呃,我該如何將此連接到Spring以及'@ ResponseBody'中的結果? – mamruoc 2012-03-22 21:47:45

2

春天讓你很容易(假設你使用Jaxb2Marshalle r):

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

我對Spring很新,但是如何指定哪個xsd到哪個'@ ResponseBody'這是我需要測試的(控制器返回一個基於組合模型的編組XML) – mamruoc 2012-03-22 21:49:09

+0

Oki,我已經添加了'',而不是增加'classesToBeBound',我用http://www.walgemoed.org/2010/12/jaxb2-spring-ws/。然而,一切運行良好,從某種意義上說,即使無效的xsd也不會給出任何錯誤消息 – mamruoc 2012-03-23 08:38:21

+0

查看http://www.ibm.com/developerworks/web/library/wa-restful/(清單4)建立一個http編組轉換器並給它上面的編組器。 – 2012-03-23 11:12:41