有 Java 编程相关的问题?

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

java我正在寻找一个HTML解析器,它可以将“small”标记替换为“span”

下面是我的代码,它解析HTML并用<span>的替换<small>标记的出现

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

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


共 (3) 个答案

  1. # 1 楼答案

    另一个解决方案是重命名标记:

    Document doc = Jsoup.parse(html);
    doc.select("small").tagName("span");
    
  2. # 2 楼答案

    它适用于所有标签:

    Document html=Jsoup.parse(htmlString);
    html.select("small").tagName("span");
    
  3. # 3 楼答案

    如果要用<span>替换所有<small>标记,则应正确使用^{}

    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>