Output JSoup without added spaces and line breaks around the elements

大憨熊 提交于 2019-12-30 18:49:19

问题


I am parsing and outputting an xml file using JSoup (and modifying the elements in between of course).

The output file has some extra spaces and line breaks. I was wondering if I can print this in the original format.

Original:

  <attributes>
        <divisions>4</divisions>
        <key>
          <fifths>0</fifths>
          <mode>major</mode>
          </key>
...

New:

<attributes> 
    <divisions>
     4
    </divisions> 
    <key> 
     <fifths>
      0
     </fifths> 
     <mode>
      major
     </mode> 
    </key> 
...

Any idea on how to remove the spaces/enters from the elements?

I currently read in and print the document like this:

doc = Jsoup.parse(is, "UTF-8", "", Parser.xmlParser());


BufferedWriter htmlWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.xml"), "UTF-8"));
        htmlWriter.write(doc.toString());

回答1:


With some help from Aleksandr M I solved it in the following way:

doc.outputSettings().indentAmount(0).prettyPrint(false);

A little less nice, but this also seemed to do the trick:

htmlWriter.write(doc.toString().replaceAll(">\\s+",">").replaceAll("\\s+<","<"));



回答2:


Try this:

doc = Jsoup.parse(is, "UTF-8", "", Parser.xmlParser());
doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
..
..

Hope this helps



来源:https://stackoverflow.com/questions/28877155/output-jsoup-without-added-spaces-and-line-breaks-around-the-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!