Pretty HTML snippet output

回眸只為那壹抹淺笑 提交于 2019-12-22 04:01:06

问题


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!


回答1:


jTidy could fit for this task - http://jtidy.sourceforge.net/howto.html

public String prettyPrintHTML(String rawHTML)
{    
    Tidy tidy = new Tidy();
    tidy.setXHTML(true);
    tidy.setIndentContent(true);
    tidy.setPrintBodyOnly(true);
    tidy.setTidyMark(false);

    // HTML to DOM
    Document htmlDOM = tidy.parseDOM(new ByteArrayInputStream(rawHTML.getBytes()), null);

    // Pretty Print
    OutputStream out = new ByteArrayOutputStream();
    tidy.pprint(htmlDOM, out);

    return out.toString();
}



回答2:


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>



回答3:


I would use HTML Tidy here is an online version.

Many of the text editors have plugins or built in functionality for this.

Sublime Text

BBEdit

Coda



来源:https://stackoverflow.com/questions/29196699/pretty-html-snippet-output

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