JAXB Marshaller indentation

被刻印的时光 ゝ 提交于 2019-12-29 07:50:10

问题


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>

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

Unfortunatelly it doesn't works for these two elements. Any ideas?


回答1:


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



回答2:


This in an JAXB error, at most 8 levels of indentation are hardcoded:

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

Source: https://community.oracle.com/thread/2351779



来源:https://stackoverflow.com/questions/46708498/jaxb-marshaller-indentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!