Strip whitespace and newlines from XML in Java

后端 未结 6 2093
半阙折子戏
半阙折子戏 2020-12-01 21:01

Using Java, I would like to take a document in the following format:


 
    
 
         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 21:56

    Java8+transformer does not create any but Java10+transformer puts everywhere empty lines. I still want to keep a pretty indents. This is my helper function to create xml string from any DOMElement instance such as doc.getDocumentElement() root node.

    public static String createXML(Element elem) throws Exception {
            DOMSource source = new DOMSource(elem);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            //transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes");
            transformer.setOutputProperty("http://www.oracle.com/xml/is-standalone", "yes");
            transformer.transform(source, result);
    
            // Java10-transformer adds unecessary empty lines, remove empty lines
            BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
            StringBuilder buf = new StringBuilder();
            try {
                final String NL = System.getProperty("line.separator", "\r\n");
                String line;
                while( (line=reader.readLine())!=null ) {
                    if (!line.trim().isEmpty()) {
                        buf.append(line); 
                        buf.append(NL);
                    }
                }
            } finally {
                reader.close();
            }
            return buf.toString();  //writer.toString();
        }
    

提交回复
热议问题