如何使用jsoup用span标记替换特定的div标签

时间:2018-05-14 07:26:07

标签: java jsoup

<div class="c45 c45v0">
    <p><span>J</span>oseph DeSimone made a bold move back</p>
</div>

我想用<div class="c45 c45v0">替换<span class="c6 c77">

<span class="c6 c77">
    <p><span>J</span>oseph DeSimone made a bold move back</p>
</span>

我尝试使用以下代码进行替换,但我无法替换它。请有人帮我解决这个问题。

if (elements.select("div.c45.c45v0").size()>0) {
    if (!elements.select("div.c45.c45v0").isEmpty()) {
        elements.tagName("span.c6.c77");
    }   
}

1 个答案:

答案 0 :(得分:1)

基于elements来自的对象的事实,您选择div.c45.c45v0它看起来不是 搜索的元素,而只是包含一个如此操纵它没有多大意义。第二件事是你不想通过tagName设置类属性。您需要通过tagName设置标记,但class属性可以通过.attr("class", "c6 c77")addClass系列(适用于新课程)和removeClass(适用于之前的课程)

演示:

String html =
        "<div class=\"c45 c45v0\">\n" +
        "    <p><span>J</span>oseph DeSimone made a bold move back</p>\n" +
        "</div>";

Document doc = Jsoup.parse(html);

//here 'elements' contain only div.c45.c45v0 elements *from* entire document (doc)
Elements elements = doc.select("div.c45.c45v0");
System.out.println(elements);

//now we can manipulate those selected elements
elements.tagName("span");
elements.attr("class", "c6 c77");
System.out.println("---------------");
System.out.println(elements);

输出:

<div class="c45 c45v0"> 
 <p><span>J</span>oseph DeSimone made a bold move back</p> 
</div>
---------------
<span class="c6 c77"> <p><span>J</span>oseph DeSimone made a bold move back</p> </span>