Create a range in DOM tree in Java

Description

The following code shows how to create a range in DOM tree.

Example


import java.io.StringReader;
/*from   ww  w.  ja v a2 s  .c o m*/
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;
import org.xml.sax.InputSource;

public class Main {
  
  public static void main(String[] argv) throws Exception {
    StringReader sr = new StringReader("<tag>java2s.com</tag>");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder loader = factory.newDocumentBuilder();

    Document document = loader.parse(new InputSource(sr));
   
    DocumentRange ranges = (DocumentRange) document;
    Element order = document.getDocumentElement();
    Range range = ranges.createRange();
    range.setStartBefore(order.getFirstChild());
    range.setEndAfter(order.getLastChild());

    range.deleteContents();
    range.detach();


  }
}




















Home »
  Java Tutorial »
    XML »




DOM
SAX