Java JDOM parser is an API in java that has classes and interfaces to modify XML documents. This API represents the XML document in the form of a tree structure and each element can be retrieved easily. Hence, modification becomes an easy task. We can use setText() to modify content and addContent() to add new elements. In this chapter, we are going to see how to modify an existing XML document with two examples.
Modify XML using JDOM Parser
We can modify an XML document in java JDOM parser through following steps −
- Step 1: Creating a SAXBuilder Object
- Step 2: Reading the XML
- Step 3: Parsing the XML Document
- Step 4: Updating the content of XML document
- Step 5: Writing the content into XML file
- Step 6: Output to console for testing
Step 4: Updating the content of XML document
After following the first three steps, we have successfully read the XML document we need to update. Now, we have the XML file in the form of JDOM document. To get any information from the document, firstly, we should always get the root element. After retrieving the root element, we can get the information of all the elements inside the root.
Updating Text Content
To update text content of any element, we can use the setText() method of Element class. This method takes the text content as an argument in the form of a String. If text content already exists, it updates the old one with the new text content.
Example
Here, we have college.xml file that has three department elements. We are going to modify the staff count for department with id, 102 from 23 to 14.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><college><department id="101"><name>Computer Science</name><staffCount>20</staffCount></department><department id="102"><name>Electrical and Electronics</name><staffCount>23</staffCount></department><department id="103"><name>Mechanical</name><staffCount>15</staffCount></department></college>
The following ModifyTextContent.java program reads the above college.xml file using SAXBuilder object. After getting the list of department elements, we are using getAttributeValue() method to find the department with id, 102. Later, we are updating the text content using setText() method.
importjava.io.File;importjava.util.List;importjavax.xml.transform.Transformer;importjavax.xml.transform.TransformerFactory;importjavax.xml.transform.stream.StreamResult;importorg.jdom2.Document;importorg.jdom2.Element;importorg.jdom2.input.SAXBuilder;importorg.jdom2.output.Format;importorg.jdom2.output.XMLOutputter;importorg.jdom2.transform.JDOMSource;publicclassModifyTextContent{publicstaticvoidmain(String args[]){try{//Creating a SAXBuilder ObjectSAXBuilder saxBuilder =newSAXBuilder();//Reading the XMLFile inputFile =newFile("college.xml");//Parsing the XML DocumentDocument doc = saxBuilder.build(inputFile);//Retrieving the Root ElementElementRootElement= doc.getRootElement();List<Element> deptList =RootElement.getChildren("department");//Finding "department" with id=102 in the listfor(int index=0; index<deptList.size();index++){Element department = deptList.get(index);if(department.getAttributeValue("id").equals("102")){Element staffCount = department.getChild("staffCount");//Updating the staff count
staffCount.setText("14");break;}}//writing the modified content into XML fileTransformerFactory transformerFactory =TransformerFactory.newInstance();Transformer transformer = transformerFactory.newTransformer();JDOMSource source =newJDOMSource(doc);StreamResult result =newStreamResult(newFile("college.xml"));
transformer.transform(source, result);//Output to console for testingXMLOutputter xmlOutput =newXMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc,System.out);}catch(Exception e){
e.printStackTrace();}}}
Output
Following is the updated XML document after updating staffCount.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><college><department id="101"><name>Computer Science</name><staffCount>20</staffCount></department><department id="102"><name>Electrical and Electronics</name><staffCount>14</staffCount></department><department id="103"><name>Mechanical</name><staffCount>15</staffCount></department></college>
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
Adding New Elements
The addContent() method of Element class takes child element and append it one level deep to the current element. It always adds the new Element at the end. If we pass two arguments, index and child element, then the child element gets inserted at the specified index.
Example
Now, we are going to add one more department named “Civil” to our college element in the following AddNewElements.java program. We have created the child elements of the department and added them to the department element. Later we added the department to the root element.
importjava.io.File;importjavax.xml.transform.Transformer;importjavax.xml.transform.TransformerFactory;importjavax.xml.transform.stream.StreamResult;importorg.jdom2.Document;importorg.jdom2.Element;importorg.jdom2.input.SAXBuilder;importorg.jdom2.output.Format;importorg.jdom2.output.XMLOutputter;importorg.jdom2.transform.JDOMSource;publicclassAddNewElements{publicstaticvoidmain(String args[]){try{//Creating a SAXBuilder ObjectSAXBuilder saxBuilder =newSAXBuilder();//Reading the XMLFile inputFile =newFile("college.xml");//Parsing the XML DocumentDocument doc = saxBuilder.build(inputFile);//Retrieving the Root ElementElementRootElement= doc.getRootElement();//Creating new "department" ElementElement department=newElement("department");
department.setAttribute("id","104");//Creating "name" Element for departmentElement name=newElement("name");
name.setText("Civil");//Creating "staffCount" Element for departmentElement staffCount=newElement("staffCount");
staffCount.setText("18");//Appending Elements
department.addContent(name);
department.addContent(staffCount);RootElement.addContent(department);//writing the modified content into XML fileTransformerFactory transformerFactory =TransformerFactory.newInstance();Transformer transformer = transformerFactory.newTransformer();JDOMSource source =newJDOMSource(doc);StreamResult result =newStreamResult(newFile("college.xml"));
transformer.transform(source, result);//Output to console for testingXMLOutputter xmlOutput =newXMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc,System.out);}catch(Exception e){
e.printStackTrace();}}}
Output
The updated file after adding “Civil” department is as follows :
<?xml version="1.0" encoding="UTF-8"?><college><department id="101"><name>Computer Science</name><staffCount>20</staffCount></department><department id="102"><name>Electrical and Electronics</name><staffCount>23</staffCount></department><department id="103"><name>Mechanical</name><staffCount>15</staffCount></department><department id="104"><name>Civil</name><staffCount>18</staffCount></department></college>
Leave a Reply