javahtmlparsingjericho-html-parser

How to parse text without nested html elements using Jericho?


Using Jericho, I need to parse something like this:

<html>
<div class="title">
    Spoon bows
    <br/>
    <span>
        A Matrix scene.
        <br/>
        Matrix 1
    </span>
</div>
</html>

I want to parse "Spoon bows", but I get the whole content within the <div> tag using the following code:

List<Element> list = item.getAllElementsByClass("title");
if(list!=null) {
    Element title = list.get(0);
    if(title!=null) {
        String text = title.getContent().getTextExtractor().toString();
        }
    }
}

Solution

  • This should help you:

    private String getTextContent(Element elem) {
        String text = elem.getContent().toString();
    
        final List<Element> children = elem.getChildElements();
        for (Element child : children) {
            text = text.replace(child.toString(), "");
        }
        return text;
    }