简体   繁体   English

使用jSoup解析最里面的html标签

[英]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. 如何解析按标签返回标签的HTML。 Loop is not covered innermost tags. 循环未覆盖最里面的标签。

Here is a well formatted html code. 这是格式正确的html代码。 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. 我想获取所有标记之间的html,作为我在html代码中显示的html层次结构。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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