【问题标题】:How I can replace "text" in the each tag using Jsoup如何使用 Jsoup 替换每个标签中的“文本”
【发布时间】:2015-08-06 03:31:58
【问题描述】:

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

感谢您的任何建议!

更新: 感谢您的回答,但我找到了通用的方法:

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

【问题讨论】:

    标签: java html replace jsoup


    【解决方案1】:

    快速搜索发现了以下代码:

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

    首先您要做的是了解该库的工作原理以及它包含哪些功能,然后您要弄清楚如何使用该库来完成您需要的工作。上面的代码似乎允许您选择一个强元素,此时您可以更新它的内部文本,但我相信您可以通过多种方式完成相同的操作。

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

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

    【讨论】:

      【解决方案2】:
      Document doc = Jsoup.connect(url).get();
      String str = doc.toString();
      str = str.replace("text", "word");
      

      试试吧..

      【讨论】:

        【解决方案3】:
            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 &gt; p表示元素&lt;div&gt;中的元素&lt;p&gt;,id为content

        如果你只想替换&lt;strong&gt;text&lt;/strong&gt;中的文字:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-23
          • 2012-03-13
          • 2011-03-13
          • 1970-01-01
          相关资源
          最近更新 更多