0

I have a StringBuilder which contains a HTML table. I want to know, if I can print this table in the console using some kind of library or anything. For example:

StringBuilder string = "<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
</table>"

I want to print this above string in a table format in console such that I do not need to specify any table information like column header or any other information.

Jhutan Debnath
  • 505
  • 3
  • 13
  • 24

1 Answers1

0

@jhutan try this one to generate the output you are looking for.

public static void main(String[] args) throws IOException {
    String html = "https://www.w3schools.com/html/html_tables.asp";
    Document doc = Jsoup.connect(html).get();
    Elements tableElements = doc.select("table");
    Elements tableHeaderEles = tableElements.select("th");
    System.out.println("headers");
    System.out.println("tableHeaderEles.size()" + tableHeaderEles.size());
    StringBuilder th = new StringBuilder();
    for (int i = 0; i < tableHeaderEles.size(); i++) {

        th.append(tableHeaderEles.get(i).text());
        th.append(" ");
    }
    System.out.println(th);

    Elements tableRowElements = tableElements.select(":not(thead) tr");
    for (int i = 0; i < tableRowElements.size(); i++) {
        Element row = tableRowElements.get(i);
        Elements rowItems = row.select("td");
        StringBuilder a = new StringBuilder();
        for (int j = 0; j < rowItems.size(); j++) {
            a.append(rowItems.get(j).text());
        }
        System.out.println(" " + a);
        //  System.out.println();
    }
}
zen
  • 5
  • 5