Edit Text by Insertion and Replacement

This Example describes a method to insert and replace
the Text in a DOM document. Methods which are used for insertion and replacement
of the text in the DOM Document are described below :-
Element root = doc.getDocumentElement():- Allows direct
access to the root of the DOM document.
Element place = (Element) root.getFirstChild():-
Retrives the first child of the root.
Text name = (Text)
place.getFirstChild().getFirstChild():-
Creates a text node and access the subchild of the node named place in it.
name.insertData(14, " Rohini "):- This is a
method to insert data in the text node. Here "Rohini " is the string
to insert and 14 specifies where to begin inserting characters.
directions.replaceData(13, 6, " Employee Roseindia"):-
This is a method to replace data in the text node. here 13 specifies value to
begin replacing characters. 6 specifies number of characters to replace.
Employee Roseindia specifies the string to insert.
XML code for the program generated is:-
<?xml version="1.0" encoding="UTF-8"?>
<Company>
<Location>
<Companyname>Roseindia .Net</Companyname>
<Employee>Girish Tewari</Employee>
</Location>
</Company>
|
EditText.java
/*
* @Program that Edit Text by Insertion and Replacement
* EditText.java
* Author:-RoseIndia Team
* Date:-10-Jun-2008
*/
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class EditText {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setValidating(false);
Document doc =
builderFactory.newDocumentBuilder().parse(new File("Document4.xml"));
new EditText().EditText(doc);
}
public void EditText(Document doc) {
int count;
int offset;
Element root = doc.getDocumentElement();
Element place = (Element) root.getFirstChild();
Text name = (Text) place.getFirstChild().getFirstChild();
Text directions = (Text) place.getLastChild().getFirstChild();
System.out.println("Name before editing is: " + name.getData());
System.out.println("Direction before editing is: " + directions.getData());
//Inserting text
name.insertData(14, " Rohini ");
System.out.println("Name after editing is: " + name.getData());
//Replacing text
directions.replaceData(13, 6, " Employee Roseindia");
System.out.println("Direction after editing is: " + directions.getData());
}
} |
Output of the program:-
Name before editing is: Roseindia .Net
Direction before editing is: Girish Tewari
Name after editing is: Roseindia .Net Rohini
Direction after editing is: Girish Tewari Employee Roseindia
|
Download
Source Code

|