How to remove extra empty lines from XML file?

前端 未结 9 1122
再見小時候
再見小時候 2020-12-08 11:22

In short; i have many empty lines generated in an XML file, and i am looking for a way to remove them as a way of leaning the file. How can i do that ?

For detailed

相关标签:
9条回答
  • 2020-12-08 11:50

    You could look at something like this if you only need to "clean" your xml quickly. Then you could have a method like:

    public static String cleanUp(String xml) {
        final StringReader reader = new StringReader(xml.trim());
        final StringWriter writer = new StringWriter();
        try {
            XmlUtil.prettyFormat(reader, writer);
            return writer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml.trim();
    }
    

    Also, to compare anche check differences, if you need it: XMLUnit

    0 讨论(0)
  • 2020-12-08 11:53

    Couple of remarks: 1) When your are manipulating XML (removing elements / adding new one) I strongly advice you to use XSLT (and not DOM) 2) When you tranform a XML Document by XSLT (as you do in your save method), set the OutputKeys.INDENT to "no" 3) For simple post processing of your xml (removing white space, comments, etc.) you can use a simple SAX2 filter

    0 讨论(0)
  • 2020-12-08 11:55
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    
    0 讨论(0)
提交回复
热议问题