Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract separate text nodes with Jsoup?

I have an element like this :

<td> TextA <br/> TextB </td>

How can I extract TextA and TextB separately?

like image 292
M.M Avatar asked Aug 23 '11 16:08

M.M


People also ask

What does jsoup parse do?

What It Is. jsoup can parse HTML files, input streams, URLs, or even strings. It eases data extraction from HTML by offering Document Object Model (DOM) traversal methods and CSS and jQuery-like selectors. jsoup can manipulate the content: the HTML element itself, its attributes, or its text.

What is a node in jsoup?

A node is the generic name for any type of object in the DOM hierarchy. An element is one specific type of node. The JSoup class model reflects this: Node.


1 Answers

Several ways. That really depends on the document itself and whether the given HTML markup is consistent or not. In this particular example you could get the td's child nodes by Element#childNodes() and then test every node individually if it's a TextNode or not.

E.g.

Element td = getItSomehow();

for (Node child : td.childNodes()) {
    if (child instanceof TextNode) {
        System.out.println(((TextNode) child).text());
    }
}

which results in

 TextA 
 TextB 

I think it would be nice if Jsoup offered a Element#textNodes() or something to get the child text nodes like as Element#children() does to get the child elements (which would have returned the <br /> element in your example).

like image 182
BalusC Avatar answered Sep 23 '22 05:09

BalusC