以下示例将HTML解析为Document对象之后,使用html,append,prepend()方法将值写入指定位置。
Document document=Jsoup.parse(html); Element div=document.getElementById("sampleDiv"); div.html("<p>This is a sample content.</p>"); div.prepend("<p>Initial Text</p>"); div.append("<p>End Text</p>");
元素对象代表dom元素,并提供各种方法来将html设置,添加或添加到dom元素。
append/prepend/html示例
使用您选择的任何编辑器在C:/> jsoup中创建以下Java程序。
JsoupTester.java
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class JsoupTester { public static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body>" + "<div id='sampleDiv'><a id='googleA' href=''>Google</a></div>" +"</body></html>"; Document document = Jsoup.parse(html); Element div = document.getElementById("sampleDiv"); System.out.println("Outer HTML Before Modification :\n" + div.outerHtml()); div.html("<p>This is a sample content.</p>"); System.out.println("Outer HTML After Modification :\n" + div.outerHtml()); div.prepend("<p>Initial Text</p>"); System.out.println("After Prepend :\n" + div.outerHtml()); div.append("<p>End Text</p>"); System.out.println("After Append :\n" + div.outerHtml()); } }
使用 javac 编译器编译类,如下所示:
C:\jsoup>javac JsoupTester.java
现在运行JsoupTester以查看输出。
C:\jsoup>java JsoupTester
查看输出。
Outer HTML Before Modification : <div id="sampleDiv"> <a id="googleA" href="">Google</a> </div> Outer HTML After Modification : <div id="sampleDiv"> <p>This is a sample content.</p> </div> After Prepend : <div id="sampleDiv"> <p>Initial Text</p> <p>This is a sample content.</p> </div> After Append : <div id="sampleDiv"> <p>Initial Text</p> <p>This is a sample content.</p> <p>End Text</p> </div> Outer HTML Before Modification : <span>Sample Content</span> Outer HTML After Modification : <span>Sample Content</span>