How to pretty print XML from Java?

后端 未结 30 2480
慢半拍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:50

    Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6.

    import org.w3c.dom.Node;
    import org.w3c.dom.bootstrap.DOMImplementationRegistry;
    import org.w3c.dom.ls.DOMImplementationLS;
    import org.w3c.dom.ls.LSSerializer;
    import org.xml.sax.InputSource;
    
    import javax.xml.parsers.DocumentBuilderFactory;
    import java.io.StringReader;
    
    /**
     * Pretty-prints xml, supplied as a string.
     * 

    * eg. * * String formattedXml = new XmlFormatter().format("hello"); * */ public class XmlFormatter { public String format(String xml) { try { final InputSource src = new InputSource(new StringReader(xml)); final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement(); final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("\n" + " \n" + " \n" + " \t\t\t\t\t ECB\n\n\n\n\n" + " \n" + " \n\n\n\n\n" + ""; System.out.println(new XmlFormatter().format(unformattedXml)); } }

提交回复
热议问题