Pretty HTML snippet output

Dmytro Pastovenskyi picture Dmytro Pastovenskyi · Mar 22, 2015 · Viewed 7.5k times · Source

I've a snippet of HTML <div><p>text1</p></div><div><p>text1</p></div>

I want to make it pretty like this

<div>
  <p>text1</p>
</div>
<div>
  <p>text1</p>
</div>

What would be most simple way to do it? (I've looked on transform and jsoup) but not sure what would be really smart to use. Thanks!

Answer

Pshemo picture Pshemo · Mar 22, 2015

You can use Jsoup like

String html = "<div><p>text1</p></div><div><p>text1</p></div>";
Document doc = Jsoup.parseBodyFragment(html);

But this will wrap your text into

<html>
  <head></head>
  <body>
    ..
  </body>
</html>

To get rid of this part you can get part from <body> like

System.out.println(doc.body().html());

which prints

<div>
 <p>text1</p>
</div>
<div>
 <p>text1</p>
</div>

If you want to increase indentation you can set it earlier with

doc.outputSettings().indentAmount(4); 

now result will look like

<div>
    <p>text1</p>
</div>
<div>
    <p>text1</p>
</div>