[英]How do I use Jsoup to insert tag before element
I need to loop though all tags of type anchor with attribute href (this is working). 我需要循环遍历所有带有属性href的anchor类型的标签(这是可行的)。 How do I then insert a NEW tag above before each anchor/href tag using JSoup? 然后,如何使用JSoup在每个anchor / href标签之前插入一个NEW标签?
EDIT: Thank you for the responses. 编辑:谢谢您的答复。 I need to clarify: Not only do I have to add new tags before href tags, but I have to nest these tags based on certain criteria. 我需要澄清:我不仅必须在href标签之前添加新标签,而且还必须根据某些条件嵌套这些标签。 How do i nest these tags? 如何嵌套这些标签?
You can use the Element
before(String html)
method. 您可以使用Element
before(String html)
方法。 Here is an example: 这是一个例子:
String html = "<div><div>Filler 1</div><div>Filler 2</div><a href=\"page.html\"/><div>Filler 3</div></div>";
Document doc = Jsoup.parse(html);
Elements elms = doc.select("a[href]");
for (Element e : elms) {
e.before("<div>Added Now</div>");
}
System.out.println(doc.html());
This will output: 这将输出:
<html>
<head></head>
<body>
<div>
<div>
Filler 1
</div>
<div>
Filler 2
</div>
<div>
Added Now
</div>
<a href="page.html"></a>
<div>
Filler 3
</div>
</div>
</body>
</html>
Use the below program, if you want to make any operations with respect to the node. 如果要对节点进行任何操作,请使用以下程序。
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.NodeVisitor;
public class InsertTagBefore {
public static void main(String... args) {
final String html = "<div><div>Filler 1</div><div>Filler 2</div><a href=\"page.html\"/><div>Filler 3</div></div>";
Document document = Jsoup.parse(html);
document.select("a").forEach(action -> { // Java 8 For Each
action.traverse(new NodeVisitor() {
/**
* method is called at the Start of the node
*
* @param node
* @param depth
*/
@Override
public void head(Node node, int depth) {
node.before("<rama>head");
}
/**
* method is called at the end of the node
*
* @param node
* @param depth
*/
@Override
public void tail(Node node, int depth) {
node.before("</rama>");
}
});
});
System.out.println(document);
}
}
I have inserted the node rama before the anchor tag. 我在锚标记之前插入了节点rama。
<html>
<head></head>
<body>
<div>
<div>Filler 1</div>
<div>Filler 2</div>
<rama> head </rama>
<a href="page.html"></a>
<div>Filler 3</div>
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.