Modify Text by Cutting and Pasting inside a DOM tree in Java

Description

The following code shows how to modify Text by Cutting and Pasting inside a DOM tree.

Example


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
//from  w ww.j  a va2  s. c  o  m
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

public class Main {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);

    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      InputSource is = new InputSource("person.xml");
      doc = builder.parse(is);

      modifyingTextbyCuttingandPasting(doc);

    } catch (Exception e) {
      System.err.println(e);
    }
  }


  public static void modifyingTextbyCuttingandPasting(Document doc) {
    Element root = doc.getDocumentElement();
    Element place = (Element)root.getFirstChild();
    Text name = (Text)place.getFirstChild().getFirstChild();
    Text directions = (Text)place.getLastChild().getFirstChild();

//    name.deleteData(offset,count);
    name.deleteData(2,3);
    
    //String bridge = directions.substringData(offset,count);
    String bridge = directions.substringData(2,3);
    name.appendData(bridge);
  }    

}

<locations>
    <place>
        <name>name</name>
        <directions>direction</directions>
    </place>
</locations>
       
   ]]>
</code>
<result><![CDATA[    
  <?xml version="1.0" standalone="yes"?>
<locations>
    <place>
        <name>
            olmedDi
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
</locations>




















Home »
  Java Tutorial »
    XML »




DOM
SAX