JAXB Marshaller缩进

时间:2017-10-12 11:31:49

标签: java xml jaxb marshalling

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

                <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文件的其余部分看起来不错。我正在使用这种方法来整理整个代码:

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

不幸的是,它不适用于这两个元素。 有什么想法吗?

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:5)

这在JAXB错误中,最多8个缩进级别是硬编码的:

IndentingUTF8XmlOutput.java:

    private void printIndent() throws IOException {
        write('\n');
        int i = depth%8;
        write( indent8.buf, 0, i*unitLen );
        i>>=3;  // really i /= 8;
        for( ; i>0; i-- )
            indent8.write(this);
    }

来源:https://community.oracle.com/thread/2351779