ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
# 解析一个body片断 <div><h2>问题</h2> <p>假如你有一个HTML片断 (比如. 一个 <code>div</code> 包含一对 <code>p</code> 标签; 一个不完整的HTML文档) 想对它进行解析。这个HTML片断可以是用户提交的一条评论或在一个CMS页面中编辑body部分。</p> <h2>办法</h2> <p>使用<code><a title="Parse a fragment of HTML, with the assumption that it forms the body of the HTML." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#parseBodyFragment%28java.lang.String%29">Jsoup.parseBodyFragment(String html)</a></code>方法.</p> <pre><code>String html = "&lt;div&gt;&lt;p&gt;Lorem ipsum.&lt;/p&gt;"; Document doc = Jsoup.parseBodyFragment(html); Element body = doc.body(); </code></pre> <h2>说明</h2> <p><code>parseBodyFragment</code> 方法创建一个空壳的文档,并插入解析过的HTML到<code>body</code>元素中。假如你使用正常的 <code><a title="Parse HTML into a Document." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#parse%28java.lang.String%29">Jsoup.parse(String html)</a></code> 方法,通常你也可以得到相同的结果,但是明确将用户输入作为 body片段处理,以确保用户所提供的任何糟糕的HTML都将被解析成body元素。</p> <p><code><a title="Accessor to the document's body element." href="http://jsoup.org/apidocs/org/jsoup/nodes/Document.html#body%28%29">Document.body()</a></code> 方法能够取得文档body元素的所有子元素,与 <code>doc.getElementsByTag("body")</code>相同。</p> <h2>保证安全Stay safe</h2> <p>假如你可以让用户输入HTML内容,那么要小心避免跨站脚本攻击。利用基于 <code><a title="Whitelists define what HTML (elements and attributes) to allow through the cleaner." href="http://jsoup.org/apidocs/org/jsoup/safety/Whitelist.html">Whitelist</a></code> 的清除器和 <code><a title="Get safe HTML from untrusted input HTML, by parsing input HTML and filtering it through a white-list of permitted tags and attributes." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#clean%28java.lang.String,%20org.jsoup.safety.Whitelist%29">clean(String bodyHtml, Whitelist whitelist)</a></code>方法来清除用户输入的恶意内容。</p><br></div>