I want to remove everything between a tag. An example input may be
Input:
<body>
  start
  <div>
    delete from below
    <div class="XYZ">
      first div having this class
      <div>
        waste
      </div>
      <div class="XYZ">
        second div having this class
      </div>
      waste
    </div>
    delete till above
  </div>
  <div>
    this will also remain
  </div>
  end
</body>
The output will be:
<body>
  start
  <div>
    delete from below
    delete till above
  </div>
  <div>
    this will also remain
  </div>
  end
</body>
Basically, I have to remove the entire block for the first occurrence of <div class="XYZ">
Thanks,
You better iterate over all elements found. so you can be shure that
Example:
Document doc = ...
for( Element element : doc.select("div.XYZ") )
{
    element.remove();
}
Edit:
( An addition to my comment )
Don't use exception handling when a simple null- / range check is enough here:
doc.select("div.XYZ").first().remove();
instead:
Elements divs = doc.select("div.XYZ");
if( !divs.isEmpty() )
{
    /*
     * Here it's safe to call 'first()' since there at least one element.
     */
}
                        Try this code :
String data = null;
    BufferedReader br = new BufferedReader(new FileReader("e://XMLFile.xml"));
    StringBuilder builder = new StringBuilder();
    while ((data = br.readLine()) != null) {
        builder.append(data);
    }
    System.out.println(builder);
    String replaceAll = builder.toString().replaceAll("<div class=\"XYZ\".+?</div>", "");
    System.out.println(replaceAll);
I have read the input XML from a file and stored it in a StringBuilder object by reading it line by line, and then replaced the entire tag will empty string.
This may help you.
 String selectTags="div,li,p,ul,ol,span,table,tr,td,address,em";
 /*selecting some specific tags */
 Elements webContentElements = parsedDoc.select(selectTags); 
 String removeTags = "img,a,form"; 
 /*Removing some tags from selected elements*/
 webContentElements.select(removeTags).remove();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With