java - Jsoup - 如何使用自动关闭创建我自己的标签
问题描述
我正在使用 JSoup 从 html 文档中提取某些标签。但是,我需要使用团队创建的一些标签来更改其中的一些。
例子
<inline id="inline-1" /> ---> <abc:123 input="1"/>
检查我的标签是否需要自结束标签。有什么线索吗?谢谢
解决方案
您可以使用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:修改属性
推荐阅读
- laravel - Laravel 5.8 - 找不到类“Arr”
- linux - 如何将 Meld 的 flatpak 版本设置为 git mergetool?
- java - 有什么方法可以将 Swift 用于 iOS 和 android 开发?
- java - 文件步行不返回绝对路径只返回文件名
- javascript - React:编辑 contentEditable div 时如何保持插入符号位置?
- linux - 哪些CPU寄存器是Linux中进程控制块(PCB)的一部分
- python - 无法对三角函数的值进行采样
- java - 在网络浏览器中隐藏 href URL
- javascript - 使用 React-Native 进行蓝牙测试
- arduino - Arduino Modbus RTU 通过串行响应?