2

我必须用新行替换几个 HTML 标记,例如您在示例代码中看到的 p 标记:

String html = "<p>Zeile1</p><p>Zeile2</p><p>Zeile3</p><p>Zeile4</p>";
Document doc = Jsoup.parse(html);
doc.select("p").append("\\n");
String sanitized = doc.text().replaceAll("\\\\n", System.getProperty("line.separator");
System.out.println(sanitized);

这是输出:

Zeile1
 Zeile2
 Zeile3
 Zeile4

如您所见,我在第 2-4 行中有空格。它们来自哪里,我该如何摆脱它们?

4

1 回答 1

3

像@bdares 建议一样,您可以遍历元素:

String html = "<p>Zeile1</p><p>Zeile2</p><p>Zeile3</p><p>Zeile4</p>";
Document doc = Jsoup.parse(html);
StringBuilder b = new StringBuilder();
for (Element p : doc.select("p")) {
    b.append(p.text());
    b.append(System.getProperty("line.separator"));
}
System.out.println(b.toString());

输出:

Zeile1
Zeile2
Zeile3
Zeile4
于 2012-04-16T13:07:09.037 回答