Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

java - JAXB Marshaller indentation

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...