Cloning a XML Element
In this section, you will learn to create a clone of a element in the DOM tree. In general, the cloning means to create a duplicate.
Description of a program:
The following program helps you in creating a clone of any element of the specified XML file. For creating a DOM object , you need the DocumentBuilderFactoty and the DocumentBuilder objects. After parsing it displays a xml file on the console using the transform() method. At run time the program asks for a element name to clone . Here the element1.cloneNode(true) method creates a clone and element1.getParentNode().insertBefore(copyElement, element1.getNextSibling()) inserts the clone element at the specified position.
Here is the XML File: Employee-Detail2.xml
<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> |
Here is the Java File: DOMCloneElements.java
import java.io.*;
|
Output of this program:
C:\vinod\xml>javac DOMCloneElements.java C:\vinod\xml>java DOMCloneElements Enter XML file name: Employee-Detail2.xml Employee-Detail2.xml file: <?xml version="1.0" encoding="UTF-8" standalone="no"?><Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> Enter the element to clone: Emp_Id Enter data to add: E011 <?xml version="1.0" encoding="UTF-8" standalone="no"?><Employee-Detail> <Employee> <Emp_Id> E-001 E011</Emp_Id><Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> |