首页 > 解决方案 > Jsoup - 如何使用自动关闭创建我自己的标签

问题描述

我正在使用 JSoup 从 html 文档中提取某些标签。但是,我需要使用团队创建的一些标签来更改其中的一些。

例子

<inline id="inline-1" />  --->  <abc:123 input="1"/>

检查我的标签是否需要自结束标签。有什么线索吗?谢谢

标签: javajsoup

解决方案


您可以使用new Element(Jsoup.parse(<(yourtagnamehere) />).body().child(0).tag(),"").html(el.html());创建一个自关闭的标签并包含要替换的标签的 html。请注意< />,确保标签自动关闭是必需的。然后,您可以使用上述元素替换所需的标签( )并使用andelement.replaceWith()设置属性。getElementsByTagName.attr()

演示代码:

import org.jsoup.parser.Parser;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities.EscapeMode;
import org.jsoup.Jsoup;
import java.util.ArrayList;
import java.util.*; 
import org.jsoup.parser.Tag;
public class MyClass {
    public static void main(String args[]) {
    String body = "<inline id=\"inline-1\" />";
    Document doc = Jsoup.parse(body);
    System.out.println("Original:\n"+doc.html()+"\n");
    System.out.println("Replaced:\n"+replaceTagWithCustom(doc, "inline", "<abc:123 />").html());
    //You can then add attribute as you want
    doc.getElementsByTag("abc:123").first().attr("input", "1");
    System.out.println("\nReplaced with attributes:\n"+doc.html());
}

    static Document replaceTagWithCustom(Document doc, String original, String replacement){
        //Can be changed to select to get multiple elements
        Element el = doc.selectFirst(original); 
        //Change tagname while conserving self closing(Note: requires format <(yourtag) /> to add self closing)
        Element el2 = new Element(Jsoup.parse(replacement).body().child(0).tag(),"").html(el.html());
        //Strip all attributes
        List<String>  attToRemove = new ArrayList<>();
        Attributes at = el.attributes();
        for (Attribute a : at) {
            attToRemove.add(a.getKey());
        }
        for(String att : attToRemove) {
            el.removeAttr(att);
        }
        el.replaceWith(el2);
        return doc;
    }
}

输出:

Original:
<html>
 <head></head>
 <body>
  <inline id="inline-1" />
 </body>
</html>

Replaced:
<html>
 <head></head>
 <body>
  <abc:123 />
 </body>
</html>

Replaced with attributes:
<html>
 <head></head>
 <body>
  <abc:123 input="1" />
 </body>
</html>

参考: 允许为标签配置自关闭- Legioth
SO:用 Jsoup 替换标签- Hardik Lotiya
SO:删除属性- Xtroce
Jsoup:修改属性


推荐阅读