21

I have an element like this :

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

How can I extract TextA and TextB separately?

1 Answer 1

26

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).

2
  • 16
    I've implemented Element#textNodes() for 1.6.2, thanks for the suggestion. github.com/jhy/jsoup/commit/… Aug 30, 2011 at 2:17
  • 2
    @JonathanHedley You're a life saver! I can't thank you enough for your hard work. Your code and comments are perfect and have saved me hours of Google and StackOverflow.
    – stackular
    Feb 4, 2014 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.