且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jsoup解析html并删除标记块

更新时间:2023-12-03 20:27:10

您***迭代找到的所有元素。所以你可以保证

You better iterate over all elements found. so you can be shure that


  • a。)所有元素都被移除并且

  • b。)如果没有元素就没有办法。

示例:

Document doc = ...

for( Element element : doc.select("div.XYZ") )
{
    element.remove();
}






编辑:

(我的评论的补充)

Don'当一个简单的 null- /范围检查足够时,使用异常处理:

Don't use exception handling when a simple null- / range check is enough here:

doc.select("div.XYZ").first().remove();

而是:

Elements divs = doc.select("div.XYZ");

if( !divs.isEmpty() )
{
    /*
     * Here it's safe to call 'first()' since there at least one element.
     */
}