【发布时间】:2021-10-12 21:44:17
【问题描述】:
我正在使用 JSoup 从 html 文档中提取某些标签。但是,我需要使用团队创建的一些标签来更改其中的一些。
例子
<inline id="inline-1" /> ---> <abc:123 input="1"/>
检查我的标签是否需要自结束标签。有什么线索吗?谢谢
【问题讨论】:
我正在使用 JSoup 从 html 文档中提取某些标签。但是,我需要使用团队创建的一些标签来更改其中的一些。
例子
<inline id="inline-1" /> ---> <abc:123 input="1"/>
检查我的标签是否需要自结束标签。有什么线索吗?谢谢
【问题讨论】:
您可以使用new Element(Jsoup.parse(<(yourtagnamehere) />).body().child(0).tag(),"").html(el.html()); 创建一个自关闭 的标签,并包含要替换的标签的html。请注意< /> 是必需的,以确保标签是自动关闭的。然后,您可以使用上述元素替换所需的标签(element.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>
参考资料:
Allow configuration of self closing for tags - Legioth
SO: Replace tags with Jsoup - Hardik Lotiya
SO: Remove attributes - Xtroce
Jsoup: modifying attributes
【讨论】: