2015-04-05 82 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> 

,我认为将是更具可读性一点比你期望的输出。