如何使用Jsoup替换每个标签中的“文本”

3

我有以下的html代码:

<html>
<head>
</head>
<body>
    <div id="content" >
         <p>text <strong>text</strong> text <em>text</em> text </p>
    </div>
</body>    
</html>

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

我期望看到:

<html>
<head>
</head>
<body>
    <div id="content" >
         <p>word <strong>word</strong> word <em>word</em> word </p>
    </div>
</body>    
</html>

感谢您的建议! 更新: 感谢回答,但我找到了一种通用的方法:
    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
            }
        }
    }
3个回答

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

试一下吧...


1
一次快速搜索找到了这段代码:

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

首先,你需要了解这个库的工作原理和包含的功能,然后确定如何使用该库来实现你需要的功能。上面的代码似乎允许你选择一个强元素,然后你可以更新其内部文本,但我相信你可以通过其他方式实现同样的效果。

通常,大多数解析XML的库都能够选择文档对象模型中的任何给定元素或任何元素列表,并操纵元素本身、其内部文本、属性等。

一旦你获得了使用不同库的经验,你的起点是查看库的文档以了解该库的功能。如果你看到一个方法说它做某事,那么它就会做那件事,你可以期望使用它来实现目标。然后,你只需要解析你正在使用的库的功能,找出如何使用它来实现你想要的功能,而不是在Stack Overflow上写一个问题。


1
    String html = "<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表示元素<p>在id为content<div>中。

如果你只想替换<strong>text</strong>中的文本:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接