How to extract content from java <div> tag

I have a serious problem. I would like to extract the content from the tag, for example:

<div class="main-content">
    <div class="sub-content">Sub content here</div>
      Main content here </div>

the output I would expect:

Sub content here Home content here

I tried using regex, but the result is not that impressive. Using:

Pattern.compile("<div>(\\S+)</div>");

will return all the lines before the first <* / div> tag so can anyone help me pls help?

+5
source share
2 answers

I would recommend avoiding regex for parsing HTML. You can easily do what you ask using Jsoup :

public static void main(String[] args) {
    String html = "<html><head/><body><div class=\"main-content\">" +
            "<div class=\"sub-content\">Sub content here</div>" +
            "Main content here </div></body></html>";
    Document document = Jsoup.parse(html);
    Elements divs = document.select("div");
    for (Element div : divs) {
        System.out.println(div.ownText());
    }
}

: div String, :

    String[] divsTexts = new String[divs.size()];
    for (int i = 0; i < divs.size(); i++) {
        divsTexts[i] = divs.get(i).ownText();
    }

: , , jquery. :

public static void main(String[] args) {
    String html = "<html><head/><body><div class=\"main-content\">" +
            "<div class=\"sub-content\">" +
            "<p>a paragraph <b>with some bold text</b></p>" +
            "Sub content here</div>" +
            "Main content here </div></body></html>";
    Document document = Jsoup.parse(html);
    Elements divs = document.select("div, p, b");
    for (Element div : divs) {
        System.out.println(div.ownText());
    }
}

HTML-:

<html>
<head />
<body>
<div class="main-content">
<div class="sub-content">
<p>a paragraph <b>with some bold text</b></p>
Sub content here</div>
Main content here</div>
</body>
</html>

:

Main content here
Sub content here
a paragraph
with some bold text
+8
<div class="main-content" id="mainCon">
    <div class="sub-content" id="subCon">Sub content here</div>
 Main content here </div>

, ,

document.getElementById("mainCon").innerHTML, sub div, .

sub-div sniplet, .. document.getElementById("subCon").innerHTML

+2

All Articles