jsoup - 将行追加到 HTML 文件

标签 jsoup java

我有一个 HTML 文件,其中包含一个行数可变的表。我希望能够打开该文件,选择表,附加一行(列数是固定的),然后将其写回文件 file。我不确定如何继续。

更新:这是一个简化但 HTML 有效的文件:

    <html>
    <head>
        <title>Light Template</title>
    </head>
    <body>
        <div class="container">
        <div class="starter-template">
        <h1>CTS QA Test Report</h1>
        <p id="suiteintrotext"></p>
        <h1>Summary</h1>
        <table class="table" id="summarytable">
            <tr>
                <th>#</th>
                <th>Test Name</th>
                <th>Author</th>
                <th>Start/End time (dur.)</th>
                <th>Avg. CPU%</th>
                <th>Pass</th>
            </tr>
            <tr>
                <td>one</td>
                <td>two</td>
                <td>three</td>
                <td>four</td>
                <td>five</td>
                <td>six</td>
            </tr>
        </table>
      </div>
    </div>
    </body>
</html>

第二行用于获取一些数据,以便在 Eclipse 中进行逐步故障排除

这是我在 Java 中所能做到的:

public void appendRow() throws ParserConfigurationException{
    File source = new File(this.Path);
    Document report = null;
    try {
        report = Jsoup.parse(source, "UTF-8");
    } catch (IOException e) {
        System.out.println("Unable to open ["+source.getAbsolutePath()+"] for parsing!");
    }
    Elements table = report.select("#summarytable");
    // Create row and td elements add append?       
}

我现在的问题是如何添加一行,它本身应该有更多元素(单元格/列)。接下来的问题是如何将其保存在 HTML 文件中?

最佳答案

        File source = new File(this.Path);
        Document report = null;
        try {
            report = Jsoup.parse(source, "UTF-8");
        } catch (IOException e) {
            System.out.println("Unable to open ["+source.getAbsolutePath()+"] for parsing!");
        }
        Elements dom = report.children();

        dom.select("#summarytable tbody").append("<tr><td>onempla</td><td>twompla</td><td>threempla</td><td>fourmpla</td><td>fivempla</td><td>sixmpla</td></tr>");

        if(!source.canWrite()) System.out.println("Can't write this file!") //Just check if the file is writable or not

        BufferedWriter bw = new BufferedWriter(new FileWriter(source));
        bw.write(dom.toString()); //toString will give all the elements as a big string
        bw.close();  //Close to apply the changes

关于jsoup - 将行追加到 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333437/

相关文章:

java - 使用 Jsoup 获取特定类的所有 href 值

java - 如何从 POST 请求获取 XML 并在 Servlet Filter 中修改它?

java - Google Cloud Bigtable 和 Java 8

java - 哪个 Android 库决定最初启动的应用程序和 Activity?

java - 如何使用问题遍历二叉树?

java - 连接字符以形成字符串会给出不同的结果

java - 如何在超时之前中断 Jsoup 获取线程?

java - 将文本文件的内容传递到 Jsoup 不会解析所有 html

java - Jsoup 从 HTML 内容中提取 Hrefs

java - jsoup 发送带有域和路径的 cookie