Parse html with jsoup and remove the tag block

后端 未结 4 1984
傲寒
傲寒 2021-01-05 06:00

I want to remove everything between a tag. An example input may be

Input:


  start
  
delete from below
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-05 06:24

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

    • a.) all elements are removed and
    • b.) there's nothing done if there's no element.

    Example:

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

    Edit:

    ( An addition to my comment )

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

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

    instead:

    Elements divs = doc.select("div.XYZ");
    
    if( !divs.isEmpty() )
    {
        /*
         * Here it's safe to call 'first()' since there at least one element.
         */
    }
    

提交回复
热议问题