1

这是我的代码,它解析 HTML 并将<small>标签<span>的出现替换为

String html =
        "<html>"+
        "<body bgcolor=''>"+
                "<table class='tabletext'>" +
                "<tr align='center' style='background:#FFFFFF'>" +
                "<td class='classa'><span id='fd'><span>10</span></span></td>" +
                "<td>10.00</td>" +
                "<td><small>&pound;0.00</small></td>" +
                "<td>&pound;280.00</td>" +
                "<td>" +
                "<ul>"+
                "<li><a href=''>ok</a></li>"+
                "</ul>"+
                "<a href='/cart.php?action=add&qty=10&id=2628' title='Click here to add this item to your cart'>" +
                "<img alt='Click here to add this item to your cart' src='/images/addtocart.gif' border='0' />" +
                "</a>" +
                "</td>" +
                "</tr>" +
                "<tr><td><span>Hello2</span></td></tr>"+
                "</table>"+
                "</body>"+
                "</html>";
        Document doc = Jsoup.parse(html);


        Elements elements = doc.select("small");


        Element element2 = elements.get(0);
        System.out.println(element2.replaceWith("<span>"));

但是上面的代码不能正常工作。

4

3 回答 3

3

如果要替换所有<small>标签,<span>则应Node.replaceWith正确使用。

Document doc = Jsoup.parse(html);
for (Element small: doc.select("small")) {
  small.replaceWith(new Element(Tag.valueOf("span"), "").text(small.text()));
}
System.out.println(doc.html()); // prints html with <small> replaced by <span>
于 2012-09-14T06:24:21.060 回答
3

另一种解决方案是重命名标签:

Document doc = Jsoup.parse(html);
doc.select("small").tagName("span");
于 2012-09-14T09:20:18.303 回答
0

它适用于所有标签:

Document html=Jsoup.parse(htmlString);
html.select("small").tagName("span");
于 2016-03-01T05:40:32.743 回答