How to pretty print XML from Java?

后端 未结 30 2509
慢半拍i
慢半拍i 2020-11-22 01:55

I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?



        
30条回答
  •  心在旅途
    2020-11-22 02:54

    As an alternative to the answers from max, codeskraps, David Easley and milosmns, have a look at my lightweight, high-performance pretty-printer library: xml-formatter

    // construct lightweight, threadsafe, instance
    PrettyPrinter prettyPrinter = PrettyPrinterBuilder.newPrettyPrinter().build();
    
    StringBuilder buffer = new StringBuilder();
    String xml = ..; // also works with char[] or Reader
    
    if(prettyPrinter.process(xml, buffer)) {
         // valid XML, print buffer
    } else {
         // invalid XML, print xml
    }
    

    Sometimes, like when running mocked SOAP services directly from file, it is good to have a pretty-printer which also handles already pretty-printed XML:

    PrettyPrinter prettyPrinter = PrettyPrinterBuilder.newPrettyPrinter().ignoreWhitespace().build();
    

    As some have commented, pretty-printing is just a way of presenting XML in a more human-readable form - whitespace strictly does not belong in your XML data.

    The library is intended for pretty-printing for logging purposes, and also includes functions for filtering (subtree removal / anonymization) and pretty-printing of XML in CDATA and Text nodes.

提交回复
热议问题