JAXB Marshaller indentation

后端 未结 2 1922
不知归路
不知归路 2020-12-19 08:21

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:

                &l         


        
相关标签:
2条回答
  • 2020-12-19 08:48

    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

    0 讨论(0)
  • 2020-12-19 08:55

    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));
    
    0 讨论(0)
提交回复
热议问题