Jsoup-set-text

提供:Dev Guides
移動先:案内検索

jsoup-テキストコンテンツの設定

次の例では、HTML文字列をDocumentオブジェクトに解析した後、dom要素にテキストを設定、追加、または追加するメソッドの使用方法を示します。

構文

Document document = Jsoup.parse(html);
Element div = document.getElementById("sampleDiv");
div.text("This is a sample content.");
div.prepend("Initial Text.");
div.append("End Text.");

どこで

  • document -ドキュメントオブジェクトはHTML DOMを表します。
  • Jsoup -指定されたHTML文字列を解析するメインクラス。
  • html -HTML文字列。
  • div -要素オブジェクトは、アンカータグを表すhtmlノード要素を表します。
  • * div.text()*-text(content)メソッドは、要素のコンテンツを対応する値に置き換えます。
  • * 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());
      div.text(This is a sample content.");
      System.out.println("Outer HTML After Modification :\n"  + div.outerHtml());
      div.prepend("Initial Text.");
      System.out.println("After Prepend :\n"  + div.outerHtml());
      div.append("End Text.");
      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">
 This is a sample content.
</div>
After Prepend :
<div id="sampleDiv">
 Initial Text.This is a sample content.
</div>
After Append :
<div id="sampleDiv">
 Initial Text.This is a sample content.End Text.
</div>