Shah
Shah

Reputation: 565

Jsoup select text after tag with many tag

I want to extract a text after each text using jsoup. Is there any way to select it?

Example code like below:

<div class="content">
<div name="panel-summary" id="summary">
    <p>
    <strong>A: </strong>*thank you* **I want to retrieve this text**<br>
    <strong>B: </strong>*Bla..bla* *I don't want this text*<br>
    <strong>C: </strong>*what ever text* *I dont want this*                         
        <strong>D: </strong>*anythinh text* *I want this*<br>
        <strong>E: </strong>*Bla..bla* *I don't want this text*t<br>
        <strong>F: </strong>*anythinh text* *I want this*<br>
    </p>

    <p>I want this</p>

and when it finish it creates auto id example id=123

Upvotes: 1

Views: 300

Answers (1)

Pshemo
Pshemo

Reputation: 124225

If we can assume that all <strong> elements which you want to find will always contain A: or D: or F: then with strong:matchesOwn(regex) (where regex will represent A:|D:|F:) we can select those elements.

After handling strong we can move on to second <p> and get its textual content via text().

String html = "<div class=\"content\">\n" +
        "<div name=\"panel-summary\" id=\"summary\">\n" +
        "    <p>\n" +
        "    <strong>A: </strong>*thank you* **I want to retrieve this text**<br>\n" +
        "    <strong>B: </strong>*Bla..bla* *I don't want this text*<br>\n" +
        "    <strong>C: </strong>*what ever text* *I dont want this*                         \n" +
        "        <strong>D: </strong>*anythinh text* *I want this*<br>\n" +
        "        <strong>E: </strong>*Bla..bla* *I don't want this text*t<br>\n" +
        "        <strong>F: </strong>*anythinh text* *I want this*<br>\n" +
        "    </p>\n" +
        "\n" +
        "    <p>I want this</p>";

Document doc = Jsoup.parse(html);
Elements pElements = doc.select("#summary p");
Elements strongElements = pElements.first().select("strong:matchesOwn(A:|D:|F:)");
for (Element strong : strongElements) {
    System.out.println(strong.nextSibling());//get next element, including textual element
}
System.out.println("---");
System.out.println(pElements.get(1).text());//textual content of <p>I want this</p>

Output:

*thank you* **I want to retrieve this text**
*anythinh text* *I want this*
*anythinh text* *I want this*
---
I want this

If you don't want to rely on content of <strong> but simply on its indexes then pick all of them like

Elements allStrElemens = doc.select("#summary p strong");

and simply pick ones you needed via their indexes (remember that indexes start from 0) like

System.out.println(allStrElemens.get(0).nextSibling());
System.out.println(allStrElemens.get(3).nextSibling());
System.out.println(allStrElemens.get(5).nextSibling());

Upvotes: 1

Related Questions