Java DOM4J API provides methods to modify XML documents. We might come across situations where we need to update few details in a large XML document. For example, an e-commerce website has many products whose price may vary on a daily or monthly basis. In such cases, modifying the already existing file makes the job simpler than to create the XML documents again. In this chapter, we are going to look at some examples to learn how to modify existing XML documents using DOM4J API.
Modify XML Using Java DOM4J Parser
Following are the steps to modify XML documents using Java DOM4J Parser −
- Step 1: Creating SAXReader object
- Step 2: Reading the XML file
- Step 3: Parsing the XML
- Step 4: Extracting the root
- Step 5: Modifying the elements
- Step 6: Creating a FileOutputStream
- Step 7: Writing the updated XML document into file
- Step 8: Printing the XML document
Step 5: Modifying the elements
After extracting the root element in step 4, we can get any of its child elements by using the elements() method. We can modify already existing elements by editing their text content, changing attribute values, adding new attributes etc.
Modify Text Content
To modify text content of an element, we can use the method setText() to set the text content. It takes a string as an argument and updates the old text content with the new text content. This method is available in both Node and Element interfaces.
Example
In the following studentData.xml file, We need to update marks from 80 to 64 for the student with roll number 493.
<?xml version="1.0" encoding="UTF-8"?><class><student rollno="393"><firstname>dinkar</firstname><lastname>kad</lastname><nickname>dinkar</nickname><marks>85</marks></student><student rollno="493"><firstname>Vaneet</firstname><lastname>Gupta</lastname><nickname>vinni</nickname><marks>80</marks></student><student rollno="593"><firstname>jasvir</firstname><lastname>singn</lastname><nickname>jazz</nickname><marks>90</marks></student></class>
The following ModifyTextContent.java program reads the above studentData.xml file using SAXReader. Using elementIterator(“student”) method, we got all the student elements in an Iterator. We iterate all the elements to find the student with roll number 493 using attributeValue() method and updates the text content of marks element.
importjava.io.File;importjava.io.FileOutputStream;importjava.util.Iterator;importorg.dom4j.Document;importorg.dom4j.Element;importorg.dom4j.io.OutputFormat;importorg.dom4j.io.SAXReader;importorg.dom4j.io.XMLWriter;publicclassModifyTextContent{publicstaticvoidmain(String[] args){try{//Creating SAXReaderSAXReader reader =newSAXReader();//Reading the XML fileFile inputFile =newFile("studentData.xml");//Parsing the XMLDocument document = reader.read(inputFile);//Extracting the rootElementRootElement= document.getRootElement();//Modifying the elementsIterator<Element> students =RootElement.elementIterator("student");while(students.hasNext()){Element student = students.next();if(student.attributeValue("rollno").equals("493")){Element marks = student.element("marks");
marks.setText("64");}}//Creating a FileOutputStreamFileOutputStream newFile =newFileOutputStream("studentData.xml");//Writing the updated XML document into fileXMLWriter writer =newXMLWriter(newFile);
writer.write( document );//Printing the XML documentOutputFormat format =OutputFormat.createPrettyPrint();XMLWriter consoleWriter =newXMLWriter(System.out, format );
consoleWriter.write( document );}catch(Exception e){
e.printStackTrace();}}}
Output
Marks for the student with roll number 493 is updated from 80 to 64.
<?xml version="1.0" encoding="UTF-8"?><class><student rollno="393"><firstname>dinkar</firstname><lastname>kad</lastname><nickname>dinkar</nickname><marks>85</marks></student><student rollno="493"><firstname>Vaneet</firstname><lastname>Gupta</lastname><nickname>vinni</nickname><marks>64</marks></student><student rollno="593"><firstname>jasvir</firstname><lastname>singn</lastname><nickname>jazz</nickname><marks>90</marks></student></class>
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
Add New Elements
The addElement() method adds new elements to an existing XML document at the end of all the already existing child elements of that current element. We need to pass the tag name of the element as an argument. Similarly, the addText() method adds text content to the element. The addAttribute() adds new attribute to the current element. We need to pass attribute name and attribute value as arguments.
The following AddNewElements.java program reads the studentData.xml file we have used in the previous example and uses the above methods to add information of a new student.
importjava.io.File;importjava.io.FileOutputStream;importorg.dom4j.Document;importorg.dom4j.Element;importorg.dom4j.io.OutputFormat;importorg.dom4j.io.SAXReader;importorg.dom4j.io.XMLWriter;publicclassAddNewElements{publicstaticvoidmain(String[] args){try{//Creating SAXReaderSAXReader reader =newSAXReader();//Reading the XML fileFile inputFile =newFile("studentData.xml");//Parsing the XMLDocument document = reader.read(inputFile);//Extracting the rootElementRootElement= document.getRootElement();//Modifying the elementsElement student =RootElement.addElement("student").addAttribute("rollno","693");
student.addElement("firstname").addText("John");
student.addElement("lastname").addText("Daniel");
student.addElement("nickname").addText("Johny");
student.addElement("marks").addText("78");//Creating a FileOutputStreamFileOutputStream newFile =newFileOutputStream("studentData.xml");//Writing the updated XML document into fileXMLWriter writer =newXMLWriter(newFile);
writer.write( document );//Printing the XML documentOutputFormat format =OutputFormat.createPrettyPrint();XMLWriter consoleWriter =newXMLWriter(System.out, format );
consoleWriter.write( document );}catch(Exception e){
e.printStackTrace();}}}
Output
The file content after adding new student information is as follows −
<?xml version="1.0" encoding="UTF-8"?><class><student rollno="393"><firstname>dinkar</firstname><lastname>kad</lastname><nickname>dinkar</nickname><marks>85</marks></student><student rollno="493"><firstname>Vaneet</firstname><lastname>Gupta</lastname><nickname>vinni</nickname><marks>64</marks></student><student rollno="593"><firstname>jasvir</firstname><lastname>singn</lastname><nickname>jazz</nickname><marks>90</marks></student><student rollno="693"><firstname>John</firstname><lastname>Daniel</lastname><nickname>Johny</nickname><marks>78</marks></student></class>
Leave a Reply