English 中文(简体)
jsoup - Set HTML
  • 时间:2024-12-22

jsoup - Set HTML


Previous Page Next Page  

Following example will showcase use of method to set, prepend or append html to a dom element after parsing an HTML String into a Document object.

Syntax

Document document = Jsoup.parse(html);
Element span = document.getElementById("sampleDiv");     
span.html("<p>This is a sample content.</p>");   
span.prepend("<p>Initial Text</p>");
span.append("<p>End Text</p>");   

Where

    document − document object represents the HTML DOM.

    Jsoup − main class to parse the given HTML String.

    html − HTML String.

    span − Element object represent the html node element representing anchor tag.

    span.html() − html(content) method replaces the element s outer html with the corresponding value.

    span.prepend() − prepend(content) method adds the content before the outer html.

    span.append() − append(content) method adds the content after the outer html.

Description

Element object represent a dom elment and provides various method to set, prepend or append html to a dom element.

Example

Create the following java program using any editor of your choice in say C:/> jsoup.

JsoupTester.java

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

pubpc class JsoupTester {
   pubpc static void main(String[] args) {
   
      String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<span id= sampleDiv ><a id= googleA  href= www.google.com >Google</a></span>"
         +"</body></html>";
      Document document = Jsoup.parse(html);

      Element span = document.getElementById("sampleDiv");
      System.out.println("Outer HTML Before Modification :
"  + span.outerHtml());
      span.html("<p>This is a sample content.</p>");
      System.out.println("Outer HTML After Modification :
"  + span.outerHtml());
      span.prepend("<p>Initial Text</p>");
      System.out.println("After Prepend :
"  + span.outerHtml());
      span.append("<p>End Text</p>");
      System.out.println("After Append :
"  + span.outerHtml());          
   }
}

Verify the result

Compile the class using javac compiler as follows:

C:jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.

C:jsoup>java JsoupTester

See the result.

Outer HTML Before Modification :
<span id="sampleDiv">
 <a id="googleA" href="www.google.com">Google</a>
</span>
Outer HTML After Modification :
<span id="sampleDiv">
 <p>This is a sample content.</p>
</span>
After Prepend :
<span id="sampleDiv">
 <p>Initial Text</p>
 <p>This is a sample content.</p>
</span>
After Append :
<span id="sampleDiv">
 <p>Initial Text</p>
 <p>This is a sample content.</p>
 <p>End Text</p>
</span>
Outer HTML Before Modification :
<span>Sample Content</span>
Outer HTML After Modification :
<span>Sample Content</span>
Advertisements