JAXB Marshaller缩进 [英] JAXB Marshaller indentation

查看:190
本文介绍了JAXB Marshaller缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JAXB marshaller来创建和格式化我的.xml文件。它工作得很好,除了一个地方。缩进缺少两个地方:

I'm using JAXB marshaller to create and format my .xml file. It works pretty well, except one place. The indentation lacks in two places:

                <Elem1>
                    <Elem2>
                        <Elem3 ID="Elem3.INFO">
                            <Elem4>INFO</Elem4>
                        </Elem3>
                        <Elem2>
                            <Elem3 ID="Elem3.TEMPLATE">
<Elem4>TEMPLATE</Elem4>
                            </Elem3>
                        </Elem2>
                        <Elem2>
                            <Elem3 ID="Elem3.LEVEL">
<Elem4>LEVEL</Elem4>
                            </Elem3>
                        </Elem2>
                    </Elem2>
                </Elem1>

.xml文件的其余部分看起来不错。我正在使用这种方法来整理整个代码:

The rest of the .xml file looks good. I'm using this method to prettify whole code:

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

不幸的是,它不适用于这两个元素。请注意,第一个< Elem4>元素格式正确。
有什么想法吗?

Unfortunatelly it doesn't works for these two elements. Please note, that the first < Elem4> element is formatted properly. Any ideas?

推荐答案

这个恼人的问题可以通过将javax Transformer应用到输出来解决。

This annoying issue could be fixed by applying javax Transformer to the output.

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.StreamResult;

Object jaxbElement = // The object you want to marshall using jaxb.

JAXBContext context = JAXBContext.newInstance(jaxbElement.getClass());
Marshaller marshaller = context.createMarshaller();
OutputStream out = // Here your destination, FileOutStream, ByteOutStream etc
DOMResult domResult = new DOMResult();
marshaller.marshal(jaxbElement, domResult);

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(new DOMSource(domResult.getNode()), new StreamResult(out));

这篇关于JAXB Marshaller缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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