有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有以下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>

谢谢你的建议

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
            }
        }
    }

共 (3) 个答案

  1. # 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表示元素<div>中的元素<p>,其id为content

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

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

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

    试试看

  3. # 3 楼答案

    快速搜索出现以下代码:

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

    等等

    首先你要做的是了解这个库是如何工作的,它包含哪些功能,然后你要弄清楚如何使用这个库来做你需要的事情。上面的代码似乎允许您选择一个强元素,在这一点上,您可以更新它的内部文本,但我相信有很多方法可以实现同样的效果

    一般来说,大多数解析xml的库都能够选择文档对象模型中的任何给定元素,或任何元素列表,并操作元素本身,或其内部文本、属性等

    一旦您获得了使用不同库的更多经验,您的出发点就是查找库的文档,看看该库的功能。如果你看到一种方法说它做了什么,它就是这样做的,你可以期望用它来实现这个目标。然后,你不需要写一个关于堆栈溢出的问题,你只需要解析你正在使用的库的功能,并找出如何使用它来做你想做的事情