有很多方法可以做到这一点。一种是使用MarshallingView和XStreamMarshaller
以下坛子首先添加到您的类路径(Maven依赖):
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.4</version>
</dependency>
然后在你的Spring XML配置
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/>
配置编组器假设你有以下你想要统帅的bean(即:显示为XML)
public class MyMessage {
private String message;
// getters & setters
}
在你的控制器类注射org.springframework.oxm.Marshaller,有你的处理方法返回一个像这样的MarshallingView:
@Controller
public class MyController {
@Autowired private Marshaller marshaller;
@RequestMapping("/helloxml")
public MarshallingView helloxml(Model model) {
MyMessage msg = new MyMessage();
msg.setMessage("hello world");
model.addAttribute("msg", msg);
MarshallingView marshallingView = new MarshallingView(marshaller);
marshallingView.setModelKey("msg"); // set what model attribute to display as xml
return marshallingView;
}
}
上面的设置会给你这样的XML当请求/helloxml
<com.gerrydevstory.xmlview.MyMessage>
<message>hello world</message>
</com.gerrydevstory.xmlview.MyMessage>
当然,如果您处理许多XML编组,那么这不是一个很好的设置。在这种情况下,您应该利用视图解析器配置。
而且XML元素的名称可得别名缩短。查看XStream文档
最后,请记住,XStream只是Spring支持的许多编码器之一,也可以考虑JAXB,Castor,Jibx等。