我被要求使用任何方法输出表中特定(正确和相同)格式的代码(但我选择了JSoup解析器,因为我认为这是最好的解决方案)。我做了一些研究并观看了教程,以便了解事情是如何运作的,但却陷入困境。
我已经尝试查看StackOverflow并发现了类似的问题,但是,我无法将以前的解决方案应用于我的任务。
我有一个包含三行和八列的表,其中每个单元格必须以特定方式进行格式化(一些格式类似,大写为整个文本,日期格式)。我正在考虑提取它们,然后尝试使用正则表达式,但是,我只设法提取每一行。
下面是我要解析的上述表格。
代码:
ArrayList<String> tableContent = new ArrayList<>();
File input = new File("[..]task_A1.html");
Document doc = Jsoup.parse(input, "UTF-8");
Element table = doc.select("table").get(0);
Elements rows = table.select("tr");
for(int i = 0; i < rows.size(); i++){
Element row = rows.get(i);
Elements cols = row.select("th");
tableContent.add(cols.text());
}
}
<table>
<tr class="primera odd">
<th class="titulo ini" scope="row">2017/10/10</th>
<th class="titulo" scope="col">Demand (b.c)</th>
<th class="titulo" scope="col">Generation(1,234.56)</th>
<th class="titulo" scope="col">Motores diesel</th>
<th class="titulo" scope="col">Turbina de gas</th>
<th class="titulo" scope="col">Fuel + Gas</th>
<th class="titulo" scope="col">Ciclo combinado (3)</th>
<th class="titulo" scope="col">Generación auxiliar (4)</th>
</tr>
<tr class="primera odd">
<th class="titulo ini" scope="row">10102017T0000</th>
<th class="titulo" scope="col">Demand (B.C)</th>
<th class="titulo" scope="col">GENERATION(1234.56)</th>
<th class="titulo" scope="col">Motores diesel</th>
<th class="titulo" scope="col">Turbina%de%gas</th>
<th class="titulo" scope="col">Fuel y Gas(3)</th>
<th class="titulo" scope="col">Ciclo combinado</th>
<th class="titulo" scope="col">Generación auxiliar (4)</th>
</tr>
<tr class="primera odd">
<th class="titulo ini" scope="row">10-10-2017</th>
<th class="titulo" scope="col">Demand (b.c)</th>
<th class="titulo" scope="col">Generation(1234,56)</th>
<th class="titulo" scope="col">Motores diesel</th>
<th class="titulo" scope="col">Turbina de gas</th>
<th class="titulo" scope="col">Fuel y Gas</th>
<th class="titulo" scope="col">Ciclo combinado</th>
<th class="titulo" scope="col">Generación.auxiliar</th>
</tr>
</table>
表:
2017/10/10需求(bc)发电量(1,234.56)柴油发动机燃料+燃气轮机联合循环(3)辅助发电机组(4)
10102017T0000需求(BC)发电(1234.56)柴油发动机涡轮%燃气和燃气%(3)联合循环辅助发电(4)
10-10-2017需求(bc)发电(1234,56)柴油发动机燃气轮机燃气和燃气联合循环辅助发电
正确的表输出:
10-10-2017需求(BC)发电(1234,56)柴油发动机燃气轮机燃气和燃气联合循环发电。辅助发电机组
10-10-2017需求(BC)发电(1234,56)柴油发动机燃气轮机燃气和燃气联合循环发电。辅助发电机组
10-10-2017需求(BC)发电(1234,56)柴油发动机燃气轮机燃气和燃气联合循环发电。辅助发电机组
问题是,如何提取/格式化/解析给定的表,以便获得相同且格式正确的所有单元格?甚至可以通过使用JSoup来完成这项任务,还是有更好的解决方案来解决这个问题?
我将不胜感激任何建议。
发布于 2019-06-06 15:53:15
您还需要遍历以下内容cols
:
for (int i = 0; i < rows.size(); i++) {
Element row = rows.get(i);
Elements cols = row.select("th");
for (int j = 0; j < cols.size(); j++) {
tableContent.add(cols.get(j).text());
}
}
因为cols
是类型elements
,可能包含几个元素(在这种情况下)。
https://stackoverflow.com/questions/-100006951
复制相似问题