简体   繁体   中英

JSoup Remove Elements

Even though, this may sound too basic, I would like to ask how do I remove an element from doc using Jsoup.

I tried searching for it, but no success.

Here is problem:

Elements myNewElements = doc.getElementsByAttribute("hello");

//Now I need to perform some other methods on myNewElements before removing.
//Hence..suggested method says,
doc.getElementsByAttribute("hello").remove();

This works fine. But I believe selecting same elements again and again could prove memory hungry. Is it possible ?

doc.select(myNewElements).remove();

//Try to select myNewElements from doc.

If you didn't add any new elements that match your inital select, you don't need to select the elements again.

Each element in elements has a reference to its parent and the remove() method just tells the parent to remove that child element.

In essence, just doing:

myNewElements.remove()

should work.

Better loop over the elements and remove them within:

for( Element element : doc.select(myNewElements) )
{
    element.remove();
}

There's a similar question: Parse html with jsoup and remove the tag block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM