Java HTML / XML How to - Check if there is an element with entered ID








Question

We would like to know how to check if there is an element with entered ID.

Answer

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
// www. j  a v  a  2 s. co  m
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Main {
  public static void main(String[] args) {
    String html = "<!html>"
  +"<html><body>"
        +"<span id='my'>"
  +"<span class=''contentTitle'>Director:</span>"
        +"<span>test</span></span>"+"</body></html>";
    
    Document doc = Jsoup.parse(html);
    System.out.println(doc.toString());

    Elements spanWithId = doc.select("span#my");

    if (spanWithId != null) {
      System.out.printf("Found %d Elements\n", spanWithId.size());

      if (!spanWithId.isEmpty()) {
        Iterator<Element> it = spanWithId.iterator();
        Element element = null;
        while (it.hasNext()) {
          element = it.next();
          System.out.println(element.toString());
        }
      }
    }
  }
}