gpt4 book ai didi

java - 如何使用jsoup编辑html标签中的所有文本值

转载 作者:行者123 更新时间:2023-11-29 02:59:52 25 4
gpt4 key购买 nike

我想要什么:我是 Jsoup 的新手。我想解析我的 html 字符串并搜索出现在标签(任何标签)内的每个文本值。然后将该文本值更改为其他值。

我所做的:我能够更改单个标签的文本值。下面是代码:

public static void main(String[] args) {
String html = "<div><p>Test Data</p> <p>HELLO World</p></div>";
Document doc1=Jsoup.parse(html);
Elements ps = doc1.getElementsByTag("p");
for (Element p : ps) {
String pText = p.text();
p.text(base64_Dummy(pText));
}
System.out.println("======================");
String changedHTML=doc1.html();
System.out.println(changedHTML);
}

public static String base64_Dummy(String abc){
return "This is changed text";
}

输出:

======================
<html>
<head></head>
<body>
<div>
<p>This is changed text</p>
<p>This is changed text</p>
</div>
</body>
</html>

以上代码可以改变p标签的值。但是,在我的例子中,html 字符串可以包含任何标签;我想搜索和更改其值。如何搜索 html 字符串中的所有标签并逐一更改它们的文本值。

最佳答案

您可以尝试使用类似于此代码的内容:

String html = "<html><body><div><p>Test Data</p> <div> <p>HELLO World</p></div></div> other text</body></html>";

Document doc = Jsoup.parse(html);
List<Node> children = doc.childNodes();

// We will search nodes in a breadth-first way
Queue<Node> nodes = new ArrayDeque<>();

nodes.addAll(doc.childNodes());

while (!nodes.isEmpty()) {
Node n = nodes.remove();

if (n instanceof TextNode && ((TextNode) n).text().trim().length() > 0) {
// Do whatever you want with n.
// Here we just print its text...
System.out.println(n.parent().nodeName()+" contains text: "+((TextNode) n).text().trim());
} else {
nodes.addAll(n.childNodes());
}
}

你会得到以下输出:

body contains text: other text
p contains text: Test Data
p contains text: HELLO World

关于java - 如何使用jsoup编辑html标签中的所有文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com