2015-04-05 66 views
0

我有以下代碼漂亮打印給定的XML。爪哇XML漂亮打印與評論塊

public void prettyPrintXML(String xmlString) { 
     try { 
      Source xmlInput = new StreamSource(new StringReader(xmlString)); 
      StringWriter stringWriter = new StringWriter(); 
      StreamResult xmlOutput = new StreamResult(stringWriter); 
      TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
      Transformer transformer = transformerFactory.newTransformer(); 
      transformer.setOutputProperty(OutputKeys.METHOD, "xml"); 
      transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); 
      transformer.transform(xmlInput, xmlOutput); 
      System.out.println("OutPutXML : "); 
      System.out.println(xmlOutput.getWriter().toString()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

這裏是上面代碼的輸入和輸出:

InputXML : 
<employees><employee><name>John</name><age>18</age></employee><!--employee><name>Smith</name><age>27</age></employee--></employees> 

OutPutXML : 
<?xml version="1.0" encoding="UTF-8"?> 
<employees> 
    <employee> 
     <name>John</name> 
     <age>18</age> 
    </employee> 
    <!--employee><name>Smith</name><age>27</age></employee--> 
</employees> 

我需要得到上面輸出的註釋塊下面的格式

<!--employee> 
    <name>Smith</name> 
    <age>27</age> 
</employee--> 

有沒有一種辦法在沒有使用任何外部庫的情況下在Java中做這個

+0

可能的重複http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java – Kishore 2015-04-05 05:08:55

+0

@Kishore,它不包含XML註釋格式。 – 2015-04-05 06:52:41

+0

問題可能不完全相同。但是答案可能與我相似或非常相似。你嘗試了那裏的建議嗎? – Kishore 2015-04-05 06:55:48

回答

1

不,這不支持使用標準庫開箱即用。獲得這種行爲需要調整很多;將註釋解析爲XML並從父節點繼承縮進級別。您還可能會將包含純文本的註釋與包含XML的註釋混合在一起。

但是,我已經實現了這樣的處理器:xmlformatter。它還可以處理文本和CDATA節點中的XML,並且可以實現強大的功能(即不會在註釋中的無效XML上失敗)。

<parent><child><!--<comment><xml/></comment>--></child></parent> 

你會得到

<parent> 
    <child> 
     <!-- 
     <comment> 
      <xml/> 
     </comment>--> 
    </child> 
</parent> 

,我認爲將是更具可讀性一點比你期望的輸出。