简体   繁体   中英

Jsoup.parse(String) - doesn't add \n

I am using Jsoup 1.7.2.

When using the API Jsoup.parse(String) I see that the output Document object adds line breaks (text line breaks, \\n) in the parsed HTML.

For example: The input string is:

<html><body><p>aaa</p></body></html>

And the Document object has the following (when calling the toString() ):

<html>
 <head></head>
 <body>
  <p>aaa</p>
 </body>
</html>

I am interested in the <body> element. How to instruct Jsoup not to format the output with new lines? I am expecting the body part to be: <body><p>aaa</p></body> .

On the other hand when I have an HTML with line breaks, I want them to remain intact.

try to do this:

Document newDocument = Jsoup.parse(htmlString, StringUtils.EMPTY, Parser.htmlParser());
newDocument.outputSettings().escapeMode(EscapeMode.base);
/**
 * Need CharEncoding.US_ASCII and not UTF-8 so the special characters will be encoded properly,
 * but representation of such will change. For instance: &mdash; will be encoded as &#8212;
 */
newDocument.outputSettings().charset(CharEncoding.US_ASCII);
newDocument.outputSettings().prettyPrint(false); // this will make sure that it will not add line breaks

Try this one. Its working

    Document doc = Jsoup.parse(String);
    // This line will keep your Html in one line
    doc.outputSettings().prettyPrint(false);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM