Java : Convert formatted xml file to one line string

前端 未结 10 1374
时光取名叫无心
时光取名叫无心 2020-12-01 04:02

I have a formatted XML file, and I want to convert it to one line string, how can I do that.

Sample xml:



        
10条回答
  •  粉色の甜心
    2020-12-01 04:39

    Using this answer which provides the code to use Dom4j to do pretty-printing, change the line that sets the output format from: createPrettyPrint() to: createCompactFormat()

    public String unPrettyPrint(final String xml){  
    
        if (StringUtils.isBlank(xml)) {
            throw new RuntimeException("xml was null or blank in unPrettyPrint()");
        }
    
        final StringWriter sw;
    
        try {
            final OutputFormat format = OutputFormat.createCompactFormat();
            final org.dom4j.Document document = DocumentHelper.parseText(xml);
            sw = new StringWriter();
            final XMLWriter writer = new XMLWriter(sw, format);
            writer.write(document);
        }
        catch (Exception e) {
            throw new RuntimeException("Error un-pretty printing xml:\n" + xml, e);
        }
        return sw.toString();
    }
    

提交回复
热议问题