[英]How do I use Jsoup to insert tag before element
我需要循環遍歷所有帶有屬性href的anchor類型的標簽(這是可行的)。 然后,如何使用JSoup在每個anchor / href標簽之前插入一個NEW標簽?
編輯:謝謝您的答復。 我需要澄清:我不僅必須在href標簽之前添加新標簽,而且還必須根據某些條件嵌套這些標簽。 如何嵌套這些標簽?
您可以使用Element
before(String html)
方法。 這是一個例子:
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());
這將輸出:
<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>
如果要對節點進行任何操作,請使用以下程序。
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);
}
}
我在錨標記之前插入了節點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.