As it was already mentioned ranges allow batch manipulation over DOM-contents. In order to create instance of a Range interface DocumentRange msut be used. Once the range is create it may be attached to a DOM-tree by two of its setters, defining range start and stop. Then the range is ready for actions. The sample below shows how the ranges can be used to delete DOM-fragment:

 import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ranges.DocumentRange;
import org.w3c.dom.ranges.Range;

 * This sample program using tree-walker for
 * non-linear traverse of DOM-document.

public class Test {
  public static void main(String[] args) {
    try {
      // load the document from a file:
      DocumentBuilderFactory factory = 
      DocumentBuilder loader = factory.newDocumentBuilder();
      Document document = loader.parse("sample.xml");

      // we are going to clean up entire order:
      Element order = document.getDocumentElement();

      // get the ranges-interface:
      DocumentRange ranges = (DocumentRange) document;

      // create and attach a range:
      Range range = ranges.createRange();

      // delete the order contents and detach the range from it:

    } catch (Exception ex) {

Parent Category: Java SE Tips