我如何将html表切割成单独的表?

时间:2013-06-14 07:32:46

标签: java html jsoup

我有一个由JSoup解析的html文档。在此表中有几行:

<table>
    <tbody>
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
    </tbody>
</table>

有些行是标题 - 我发现这些行有Jsoup select(...)方法。所以我有Elements对象包含所有标题行。让我们说它看起来像这样:

<table>
    <tbody>
        <tr id="tr1">...</tr> 
        <tr id="tr2">...</tr> // this is header
        <tr id="tr3">...</tr>
        <tr id="tr4">...</tr>
        <tr id="tr5">...</tr> // this is header
        <tr id="tr6">...</tr>
    </tbody>
</table>

Id属性仅适用于此示例 - int real case在解析的html中没有id属性。

我需要的是获得2个表(包含每个表的2个Element个对象),每个表一个,包含给定标题下方但下一个标题下方的所有行。所以我希望:

<table> // Element 1
    <tbody>
        <tr id="tr3">...</tr>
        <tr id="tr4">...</tr>
    </tbody>
</table>

<table> // Element 2
    <tbody>
        <tr id="tr6">...</tr>
    </tbody>
</table>

any1可以帮我完成这项任务吗?

1 个答案:

答案 0 :(得分:1)

测试JSoup的dom处理能力是一个很好的练习。以下是您需要的代码段。代码几乎是不言自明的(createElement创建一个元素等等),但如果您需要任何澄清,请告诉我:

Elements tables = new Elements();
for (Element headerTR : headerRows) {
    Element tbody = doc.createElement("tbody");
    Element firstSiblingTR = headerTR.nextElementSibling();
    if (firstSiblingTR != null) {
        Element secondSiblingTR = firstSiblingTR.nextElementSibling();
        tbody.appendChild(firstSiblingTR);
        if (secondSiblingTR != null) {
            tbody.appendChild(secondSiblingTR);
        }
    }
    Element table = doc.createElement("table");
    table.appendChild(tbody);
    tables.add(table);
}

使用示例:

public static void main(String[] args) {
    Document doc = Jsoup.parse("<html><body>"+
    "<table>" +
    "  <tbody>" +
    "    <tr><td>1</td></tr>" +
    "    <tr class='header'><td>2</td></tr>" + // class added to simulate ur list
    "    <tr><td>3</td></tr>" +
    "    <tr><td>4</td></tr>" +
    "    <tr class='header'><td>5</td></tr>" + // class added to simulate ur list
    "    <tr><td>6</td></tr>" +
    "  </tbody>" +
    "</table>" +
    "</body></html>");

    Elements headerRows = doc.getElementsByClass("header"); // simulating ur list

    Elements tables = new Elements();
    for (Element headerTR : headerRows) {
        Element tbody = doc.createElement("tbody");
        Element firstSiblingTR = headerTR.nextElementSibling();
        if (firstSiblingTR != null) {
            Element secondSiblingTR = firstSiblingTR.nextElementSibling();
            tbody.appendChild(firstSiblingTR);
            if (secondSiblingTR != null) {
                tbody.appendChild(secondSiblingTR);
            }
        }
        Element table = doc.createElement("table");
        table.appendChild(tbody);
        tables.add(table);
    }
    System.out.println(tables); // print <table> list
}

输出:

<table>
    <tbody>
        <tr><td>3</td></tr>
        <tr><td>4</td></tr>
    </tbody>
</table>
<table>
    <tbody>
        <tr><td>6</td></tr>
    </tbody>
</table>