2017-10-12 82 views
1

我正在使用JAXB marshaller來創建和格式化我的.xml文件。它工作得很好,除了一個地方。縮進缺少兩處:JAXB Marshaller indentation

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

不幸的是,它不適用於這兩個元素。請注意,第一個< Elem4>元素格式正確。 任何想法?

回答

1

這惱人的問題可以通過應用的javax變壓器的輸出加以固定。

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

這在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