简体   繁体   中英

How to remove one element from another with JSoup?

For example, in this element:

<b><a id="Dr_Michael_Moriarty">Michael Moriarty</a> and Moriartybitcoin</b>

How can one remove

<a id="Dr_Michael_Moriarty">Michael Moriarty</a> 

from the original element to obtain "and Moriartybitcoin" as String? Apparently "element.empty()" does not work.

You can remove() elements from DOM.

Demo:

String text = "<b><a id=\"Dr_Michael_Moriarty\">Michael Moriarty</a> and Moriartybitcoin</b>";
Document doc = Jsoup.parse(text);

Elements bElement = doc.select("b");

System.out.println(bElement);
bElement.select("a").remove();

System.out.println(bElement);
System.out.println(bElement.text());

Output:

<b><a id="Dr_Michael_Moriarty">Michael Moriarty</a> and Moriartybitcoin</b>
<b> and Moriartybitcoin</b>
and Moriartybitcoin

You see here original b element, then with removed a , and text represented by such element after removal.

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