以下示例将展示使用方法在将HTML字符串解析为Document对象后将html设置,预置或附加到dom元素.
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>");
其中
文件 : document对象代表HTML DOM.
Jsoup : 用于解析给定HTML字符串的主类.
html : HTML字符串.
div : Element对象表示代表锚标记的html节点元素.
div.html() : html(content)方法用相应的值替换元素的外部html.
div.prepend() : prepend(content)方法在外部html之前添加内容.
div.append() : append(content)方法在外部html之后添加内容.
元素对象代表一个dom elment并提供各种方法来设置,添加或附加html到dom元素.
使用任何创建以下java程序你选择的编辑说C:/> jsoup.
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='www.google.com'>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="www.google.com">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>