Java HTML / XML How to - Get first level table cell








Question

We would like to know how to get first level table cell.

Answer

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/*from  ww w  .j  a v  a 2s .c  o  m*/
public class Main {
    public static void main(String[] args) {
        String html = 
                "<html>                        " +
                "  <body>                      " +
                "    <table id='myTable'>      " +
                "      <tbody>                 " +
                "        <tr>                  " +
                "          <th>header</th>     " +
                "          <td>1</td>          " +
                "            <table>           " +
                "              <tbody>         " +
                "                <tr>          " +
                "                  <td>a1</td> " +
                "                  <td>a2</td> " +
                "                  <td>a3</td> " +
                "                </tr>         " +
                "              </tbody>        " +
                "            </table>          " +
                "          </td>               " +
                "          <td>high level2</td>" +
                "          <td>high level3</td>" +
                "        </tr>                 " +
                "      </tbody>                " +
                "    </table>                  " +
                "  </body>                     " +
                "</html>                       ";
        Document doc = Jsoup.parse(html);
        Elements highLevelTDs = doc.select("#myTable > tbody > tr > td");
        System.out.println(highLevelTDs.size());
        for (Element td : highLevelTDs) {
            System.out.println(td);
        }
    }
}