How to Update XML File in Java


Here this example will provide a simple method to modify XML file in Java.

Source Code

(1)Test.xml



  
    Alice
Pairs

 

(2)ModifyXML.java

package com.beginner.examples;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class ModifyXML {

	public static void main(String[] args) throws JDOMException, IOException {

		SAXBuilder saxBuilder = new SAXBuilder();
		File xmlFile = new File("Test.xml");
		
		Document doc = (Document) saxBuilder.build(xmlFile);
		Element root = doc.getRootElement();
		
		Element param = root.getChild("staff");
		param.getAttribute("name").setValue("Bob");
		
		XMLOutputter xmlOutput = new XMLOutputter();
		xmlOutput.setFormat(Format.getPrettyFormat());
		xmlOutput.output(doc, new FileWriter("Test.xml"));

	}

}

Output:


  
    Alice
Pairs

 

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments