Edit Text by Insertion and Replacement inside a DOM tree in Java

Description

The following code shows how to edit Text by Insertion and Replacement inside a DOM tree.

Example


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
//from  ww  w  . ja v a  2 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("personWithDTD.xml");
      doc = builder.parse(is);

      editTextbyInsertionandReplacement(doc);

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


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

    // Inserting the word "black"
//    name.insertData(offset," black");
    name.insertData(3," black");

    // Replace "left" with "right"
    //directions.replaceData(offset,count,"right");
    directions.replaceData(3,3,"right");
  }


}


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




















Home »
  Java Tutorial »
    XML »




DOM
SAX