繁体   English   中英

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

[英]How I can replace “text” in the each tag using Jsoup

我有以下html:

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

如何使用Jsoup库在每个标签中将 “文本”替换为“单词”。 我想看看:

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

感谢您的任何建议!

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));

等等

首先,您要了解的是库的工作方式以及它包含的功能,然后您要弄清楚如何使用该库来完成所需的工作。 上面的代码似乎允许您选择一个较强的元素,这时您可以更新它的内部文本,但是我敢肯定,可以通过多种方法来实现相同的目的。

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

一旦获得了使用其他库的更多经验,您的出发点便是查找库的文档,以了解该库的功能。 如果您看到一个说它可以完成某件事的方法,那就是它所做的,并且您可以期望使用它来实现该目标。 然后,您无需解析有关Stack Overflow的问题,只需解析正在使用的库的功能,并弄清楚如何使用它来完成所需的工作。

    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表示id为content的元素<div>中的元素<p>

如果您只想替换<strong>text</strong>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM