我有一个 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/