简体   繁体   中英

Parse the inner most html tags using jSoup

Here is my code.

String tags="<html><head></head><body><table><tr><td>1</td></tr><tr><td><table><tr><td>3</td><td>4</td></tr></table></td></tr></table><body></html>";
        Document document = Jsoup.parse(tags);
        for(int i=0;i<document.body().childNodes().size();i++)
        {
            if(!document.body().childNodes().get(i).nodeName().startsWith("#"))
            {
                System.out.println("1st Level Nodes:"+document.body().childNodes().get(i).nodeName());
                while(document.body().childNodes().get(i).childNodes().size()>1)
                {
                    System.out.println("2nd Level: "+document.body().childNodes().get(i).childNodes().get(0).nodeName());
                }
            }
        }

How to parse the HTML which return tag by tag. Loop is not covered innermost tags.

Here is a well formatted html code. Parse the all the tags to inner most.

<html>
<head></head>
<body>
<table>
    <tr>
        <td>1</td>
    </tr>

    <tr>
        <td>
            <table>
            <tr>
                <td>3</td>
                <td>4</td>
            </tr>
            </table>
        </td>
    </tr>
</table>
<body>
</html>

I want to get all the html in between tag as a hierarchy of html which i shown in html code. So i like to get all the tag one after another as per sequence of parent and child.

If you need only the tags you can use this here:

String tags = "<html><head></head><body><table><tr><td>1</td></tr><tr><td><table><tr><td>3</td><td>4</td></tr></table></td></tr></table><body></html>";
Document doc = Jsoup.parse(tags);


for( Element e : doc.select("*") // you can use 'doc.getAllElements()' here too
{
    System.out.println(e.tag());
}

Output:

#root
html
head
body
table
tbody
tr
td
tr
td
table
tbody
tr
td
td

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM