Jsoup-set-html
提供:Dev Guides
jsoup-HTMLを設定する
次の例では、HTML文字列をDocumentオブジェクトに解析した後、dom要素にhtmlを設定、追加、または追加するメソッドの使用方法を示します。
構文
Document document = Jsoup.parse(html);
Element div = document.getElementById("sampleDiv");
divl("<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 -要素オブジェクトは、アンカータグを表すhtmlノード要素を表します。
- * divl()*-html(content)メソッドは、要素の外側のhtmlを対応する値に置き換えます。
- * div.prepend()*-prepend(content)メソッドは、外側のhtmlの前にコンテンツを追加します。
- * div.append()*-append(content)メソッドは、外側のhtmlの後にコンテンツを追加します。
説明
Elementオブジェクトはdom要素を表し、htmlをdom要素に設定、追加、追加するためのさまざまなメソッドを提供します。
例
たとえば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='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());
divl("<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>