是否有用于查询 HTML 表的 SQL 包装器

Is there an SQL wrapper to query an HTML table

本文关键字:SQL 包装 表的 HTML 用于 查询 是否      更新时间:2023-10-16

关于如何将SQL查询的结果格式化为HTML表有很多问题,但我想走另一条路 - 给定一个带有标题行的任意HTML表,我希望能够使用SQL(或类似SQL的语言)从一行或多行中提取信息。陈述起来很简单,但显然不是那么容易完成。

最终,我更喜欢使用 libtidy 或 JSoup 之类的东西正确解析 HTML,但是虽然 API 文档通常是合理的,但当涉及到实际使用它们的示例或教程时,您通常会找到一个提取

标签的示例(可以使用正则表达式完成),没有如何使用库的真实示例。因此,对于现有的已建立的库之一,一个好的资源或示例代码也会很好。

使用 JSoup 将表转换为元组列表的简单代码如下所示:

public class Main {
    public static void main(String[] args) throws Exception {
        final String html = 
            "<html><head/><body>" +
                "<table id="example">" +
                    "<tr><td>John</td><td>Doe</td></tr>" +
                    "<tr><td>Michael</td><td>Smith</td>" +
                "</table>" +
            "</body></html>";
        final List<Tuple> tuples = parse (html, "example");
                    //... Here the table is parsed
    }
    private static final List<Tuple> parse(final String html, final String tableId) {
        final List<Tuple> tuples = new LinkedList<Tuple> ();
        final Element table = Jsoup.parse (html).getElementById(tableId);
        final Elements rows = table.getElementsByTag("tr");
        for (final Element row : rows) {
            final Elements children = row.children();
            final int childCount = children.size(); 
            final Tuple tuple = new Tuple (childCount);
            for (final Element child : children) {
                tuple.addColumn (child.text ());
            }
        }
        return tuples;
    }
}
public final class Tuple {
    private final String[] columns;
    private int cursor;
    public Tuple (final int size) {
        columns = new String[size];
        cursor = 0;
    }
    public String getColumn (final int no) {
        return columns[no];
    }
    public void addColumn(final String value) {
        columns[cursor++] = value;
    }
}

从这里开始,您可以例如使用 H2 创建一个内存表并使用常规 SQL。