日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Jsoup代码解读之三-Document的输出

發布時間:2023/12/3 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Jsoup代码解读之三-Document的输出 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

轉載自? ?Jsoup代碼解讀之三-Document的輸出

Jsoup官方說明里,一個重要的功能就是***output tidy HTML***。這里我們看看Jsoup是如何輸出HTML的。

HTML相關知識

分析代碼前,我們不妨先想想,"tidy HTML"到底包括哪些東西:

  • 換行,塊級標簽習慣上都會獨占一行
  • 縮進,根據HTML標簽嵌套層數,行首縮進會不同
  • 嚴格的標簽閉合,如果是可以自閉合的標簽并且沒有內容,則進行自閉合
  • HTML實體的轉義

這里要補充一下HTML標簽的知識。HTML Tag可以分為block和inline兩類。關于Tag的inline和block的定義可以參考http://www.w3schools.com/html/html_blocks.asp,而Jsoup的Tag類則是對Java開發者非常好的學習資料。

<!-- lang: java --> // internal static initialisers: // prepped from http://www.w3.org/TR/REC-html40/sgml/dtd.html and other sources //block tags,需要換行 private static final String[] blockTags = {"html", "head", "body", "frameset", "script", "noscript", "style", "meta", "link", "title", "frame","noframes", "section", "nav", "aside", "hgroup", "header", "footer", "p", "h1", "h2", "h3", "h4", "h5", "h6","ul", "ol", "pre", "div", "blockquote", "hr", "address", "figure", "figcaption", "form", "fieldset", "ins","del", "s", "dl", "dt", "dd", "li", "table", "caption", "thead", "tfoot", "tbody", "colgroup", "col", "tr", "th","td", "video", "audio", "canvas", "details", "menu", "plaintext" }; //inline tags,無需換行 private static final String[] inlineTags = {"object", "base", "font", "tt", "i", "b", "u", "big", "small", "em", "strong", "dfn", "code", "samp", "kbd","var", "cite", "abbr", "time", "acronym", "mark", "ruby", "rt", "rp", "a", "img", "br", "wbr", "map", "q","sub", "sup", "bdo", "iframe", "embed", "span", "input", "select", "textarea", "label", "button", "optgroup","option", "legend", "datalist", "keygen", "output", "progress", "meter", "area", "param", "source", "track","summary", "command", "device" }; //emptyTags是不能有內容的標簽,這類標簽都是可以自閉合的 private static final String[] emptyTags = {"meta", "link", "base", "frame", "img", "br", "wbr", "embed", "hr", "input", "keygen", "col", "command","device" }; private static final String[] formatAsInlineTags = {"title", "a", "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "address", "li", "th", "td", "script", "style","ins", "del", "s" }; //在這些標簽里,需要保留空格 private static final String[] preserveWhitespaceTags = {"pre", "plaintext", "title", "textarea" };

另外,Jsoup的Entities類里包含了一些HTML實體轉義的東西。這些轉義的對應數據保存在entities-full.properties和entities-base.properties里。

Jsoup的格式化實現

在Jsoup里,直接調用Document.toString()(繼承自Element),即可對文檔進行輸出。另外OutputSettings可以控制輸出格式,主要是prettyPrint(是否重新格式化)、outline(是否強制所有標簽換行)、indentAmount(縮進長度)等。

里面的繼承和互相調用關系略微復雜,大概是這樣子:

Document.toString()=>Document.outerHtml()=>Element.html(),最終Element.html()又會循環調用所有子元素的outerHtml(),拼接起來作為輸出。

<!-- lang: java --> private void html(StringBuilder accum) {for (Node node : childNodes)node.outerHtml(accum); }

而outerHtml()會使用一個OuterHtmlVisitor對所以子節點做遍歷,并拼裝起來作為結果。

<!-- lang: java --> protected void outerHtml(StringBuilder accum) {new NodeTraversor(new OuterHtmlVisitor(accum, getOutputSettings())).traverse(this); }

OuterHtmlVisitor會對所有子節點做遍歷,并調用node.outerHtmlHead()和node.outerHtmlTail兩個方法。

<!-- lang: java --> private static class OuterHtmlVisitor implements NodeVisitor {private StringBuilder accum;private Document.OutputSettings out;public void head(Node node, int depth) {node.outerHtmlHead(accum, depth, out);}public void tail(Node node, int depth) {if (!node.nodeName().equals("#text")) // saves a void hit.node.outerHtmlTail(accum, depth, out);} }

我們終于找到了真正工作的代碼,node.outerHtmlHead()和node.outerHtmlTail。Jsoup里每種Node的輸出方式都不太一樣,這里只講講兩種主要節點:Element和TextNode。Element是格式化的主要對象,它的兩個方法代碼如下:

<!-- lang: java --> void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out) {if (accum.length() > 0 && out.prettyPrint()&& (tag.formatAsBlock() || (parent() != null && parent().tag().formatAsBlock()) || out.outline()) )//換行并調整縮進indent(accum, depth, out);accum.append("<").append(tagName());attributes.html(accum, out);if (childNodes.isEmpty() && tag.isSelfClosing())accum.append(" />");elseaccum.append(">"); }void outerHtmlTail(StringBuilder accum, int depth, Document.OutputSettings out) {if (!(childNodes.isEmpty() && tag.isSelfClosing())) {if (out.prettyPrint() && (!childNodes.isEmpty() && (tag.formatAsBlock() || (out.outline() && (childNodes.size()>1 || (childNodes.size()==1 && !(childNodes.get(0) instanceof TextNode)))))))//換行并調整縮進indent(accum, depth, out);accum.append("</").append(tagName()).append(">");} }

而ident方法的代碼只有一行:

<!-- lang: java --> protected void indent(StringBuilder accum, int depth, Document.OutputSettings out) {//out.indentAmount()是縮進長度,默認是1accum.append("\n").append(StringUtil.padding(depth * out.indentAmount())); }

代碼簡單明了,就沒什么好說的了。值得一提的是,StringUtil.padding()方法為了減少字符串生成,把常用的縮進保存到了一個數組中。

好了,水了一篇文章,下一篇將比較有技術含量的parser部分。

另外,通過本節的學習,我們學到了要把StringBuilder命名為accum,而不是sb


總結

以上是生活随笔為你收集整理的Jsoup代码解读之三-Document的输出的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。