Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsoup prevent pretty print

Tags:

java

jsoup

If I do something like this with a jsoup Element

new Element("div").html("<p></p>")

The output of the toString() method (or for that case the outerHtml()) method yields something like this.

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

I cannot find anything in the documentation that says it adds newlines or spaces to whatever is added to Element.

Is there any way to output it like that:

<div><p></p></div>
like image 898
Tom Avatar asked Aug 31 '25 20:08

Tom


1 Answers

From what I can tell, pretty print settings are set on the Document level.

You can get and set the setting, like so:

// Document doc = ...
doc.outputSettings().prettyPrint();      // true by default
doc.outputSettings().prettyPrint(false); // set to false to disable "pretty print"

Here is how one can cook up an empty Document:

Document doc = new Document("");
// use Jsoup.parse("") if you don't mind the basic HTML stub:
// html, head, and body.

This is what I would do to print your Element "as is" - without new lines:

Document doc = new Document("");
doc.outputSettings().prettyPrint(false);
doc.insertChildren(0, new Element("div").html("<p></p>"));
System.out.println(doc);
// prints: <div><p></p></div>

References

  • Document.OutputSettings#prettyPrint(boolean)
  • Document.OutputSettings#prettyPrint()
like image 106
Janez Kuhar Avatar answered Sep 03 '25 08:09

Janez Kuhar