在CXF中格式化XML输出? [英] Formatted XML output in CXF?

查看:482
本文介绍了在CXF中格式化XML输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用Marshaller时如何打开格式的可能性.但是我正在使用Apache CXF(JAX-RS)并返回类似return Response.ok(entity).build();的响应.

I know about the possibility how to turn on the formatting when using Marshaller. But I'm using Apache CXF (JAX-RS) and returning a response like return Response.ok(entity).build();.

我还没有找到如何格式化输出的任何选项.我该怎么办?

I haven't found any option how to format the output. How can I do it?

推荐答案

首先,获取XML格式化输出的方法是在编组器上设置正确的属性(通常在使用CXF时使用JAXB,自JAXB以来就可以了)做得很可靠).也就是说,在某个地方您将需要执行以下操作:

First off, the way to get formatted output of XML is to set the right property on the marshaller (typically JAXB when working with CXF, which is OK since JAXB does a creditable job). That is, somewhere you're going to have something doing this:

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

问题是您不一定要格式化 all 所有输出;它增加了很多开销.幸运的是,您已经在生成一个显式的Response,因此我们可以使用该功能的更多功能:

The issue is that you don't necessarily want to have all output formatted; it adds quite a bit to the overhead. Luckily, you're already producing an explicit Response, so we can just use more features of that:

Marshaller marshaller = JAXBContext.newInstance(entity.getClass()).createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
marshaller.marshal(entity, sw);

return Response.ok(sw.toString(), MediaType.APPLICATION_XML_TYPE).build();


此JIRA问题中提到了另一种方法(该方法本身已经关闭,但是并没有那么多给您的问题):


Another method is mentioned in this JIRA issue (itself closed, but that's not so much of an issue for you):

解决方法是注册一个自定义输出处理程序,该处理程序可以检查用于请求可选缩进的任何自定义查询:

The workaround is to register a custom output handler which can check whatever custom query is used to request the optional indentation:

http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/FormatResponseHandler.java

JAXBElementProvider和JSONProvider由JAXB Marshaller驱动,因此默认情况下,它们会检查当前消息上的Marshaller.JAXB_FORMATTED_OUTPUT属性.

JAXBElementProvider and JSONProvider are driven by the JAXB Marshaller so by default they check a Marshaller.JAXB_FORMATTED_OUTPUT property on the current message.

这将导致如下代码:

public class FormattedJAXBInterceptor extends AbstractPhaseInterceptor<Message> {
    public FormattedJAXBInterceptor() {
        super(Phase.PRE_STREAM);
    }

    public void handleMessage(Message message) {
        message.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    }

    public void handleFault(Message messageParam) {
        message.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    }
}

CXF网站讨论拦截器的注册.

这篇关于在CXF中格式化XML输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆