2014-03-25 24 views
0

我有一個java代碼,它使用DOM解析策略將輸出寫入XML。是XML的寫作之後的內容如下現在如何在從java重寫xml時保持相同的縮進?

<L-1><?xm-replace_text {L-1}?></L-1> 

,如果我做一些改變後重寫相同的XML,XML的寫作後的內容將如下

<L-1> 
            <?xm-replace_text {L-1}?> 
           </L-1> 

我使用每次我寫XML時都使用相同的變壓器

 encoding = (doc.getXmlEncoding() != null) ? doc.getXmlEncoding() 
       : "iso-8859-1"; 
     version = (doc.getXmlVersion() != null) ? doc.getXmlVersion() 
       : "1.0"; 

TransformerFactory tFactory = TransformerFactory.newInstance(); 
Transformer transformer = tFactory.newTransformer(); 
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
transformer.setOutputProperty(OutputKeys.ENCODING, encoding); 
transformer.setOutputProperty(OutputKeys.VERSION, version); 

爲什麼我有縮進問題?

回答

0

您應該指定的金額縮進

transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
String propertyFormat1 = "b;http://xml.apache.org/xsltd;indent-amount"; 
String propertyFormat2 = "{http://xml.apache.org/xslt}indent-amount"; 

// this 
// transformer.setOutputProperty(propertyFormat1 , "2"); 
// or, the following 
transformer.setOutputProperty(propertyFormat2, "2"); 

參考一些實施例

  1. FormattinganXMLfileusingTransformer
  2. Java: How to Indent XML Generated by Transformer(開SO)
相關問題