在CXF中格式化XML输出?

一时失言乱红尘 2024-04-03 13:52 185阅读 0赞

  在CXF中格式化XML输出? \_在CXF中格式化XML输出?

  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?

  盾畳圭宛

  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);

  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();

  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 and JSONProvider are driven by the JAXB Marshaller so by default they check a Marshaller.JAXB_FORMATTED_OUTPUT property on the current message.

  This leads to code like this:

  public class FormattedJAXBInterceptor extends AbstractPhaseInterceptor {

  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);

  }

  }

  The CXF site discusses registration of interceptors.

发表评论

表情:
评论列表 (有 0 条评论,185人围观)

还没有评论,来说两句吧...

相关阅读

    相关 输出格式化xml文件

      上一篇我按照网上的资源写了一个创建xml文件的小程序,算让创建成功,但是在新增节点时发现格式不对,没有成xml的树状而是一行,详见我在简书的 创建xml文件系统 http: