如何使用Jsoup替换每个标记中的“text”

我有以下html:

    

text text text text text

如何使用Jsoup库将“text”替换为每个标记中的“word”。 我想看看:

     

word word word word word

谢谢你的任何建议!

UPD:谢谢你的回答,但我找到了多种方式:

  Element entry = doc.select("div").first(); Elements tags = entry.getAllElements(); for (Element tag : tags) { for (Node child : tag.childNodes()) { if (child instanceof TextNode && !((TextNode) child).isBlank()) { System.out.println(child); //text ((TextNode) child).text("word"); //replace to word } } } 

 Document doc = Jsoup.connect(url).get(); String str = doc.toString(); str = str.replace("text", "word"); 

试试吧..

快速搜索出现了这段代码:

 Elements strongs = doc.select("strong"); Element f = strongs.first(); Element l = strongs.last();1,siblings.lastIndexOf(l)); 

等等

首先,您要了解的是库的工作原理以及它包含的function,然后您将了解如何使用库来执行您需要的操作。 上面的代码似乎允许您选择一个强大的元素,此时您可以更新它的内部文本,但我确信有很多方法可以完成相同的操作。

通常,解析xml的大多数库能够选择文档对象模型中的任何给定元素或任何元素列表,并且可以操纵元素本身,或者它们的内部文本,属性等。

一旦您获得了使用不同库的更多经验,您的出发点是查找库的文档以查看该库的function。 如果你看到一种方法表明它做了什么,那就是它的作用,你可以期望用它来实现这个目标。 然后,您只需解析您正在使用的库的function,而不是在Stack Overflow上编写问题,并找出如何使用它来执行您想要的操作。

  String html = " ..."; Document doc = Jsoup.parse(html); Elements p = doc.select("div#content > p"); p.html(p.html().replaceAll("text", "word")); System.out.println(doc.toString()); 

div#content > p表示元素

中的元素

,其中id是content

如果您只想在text替换文字:

  Elements p = doc.select("div#content > p > strong"); p.html(p.html().replaceAll("text", "word"));