How to modify XML file in Java – (JDOM Parser)
Published: April 3, 2010 , Updated: August 4, 2011 , Author: mkyong
JDOM XML parser example to modify an existing XML file :
- Add a new element
- Update existing element attribute
- Update existing element value
- Delete existing element
1. XML File
See before and after XML file.
File : file.xml – Original XML file.
<?xml version="1.0" encoding="UTF-8"?> <company> <staff id="1"> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>5000</salary> </staff> </company>
Later, update above XML file via JDOM XML Parser.
- Add a new “age” element under staff
- Update the staff attribute id = 2
- Update salary value to 7000
- Delete “firstname” element under staff
File : file.xml – Newly modified XML file.
<?xml version="1.0" encoding="UTF-8"?> <company> <staff id="2"> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>7000</salary> <age>28</age> </staff> </company>
2. JDOM Example
JDOM parser to update or modify an existing XML file.
import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; public class ModifyXMLFile { public static void main(String[] args) { try { SAXBuilder builder = new SAXBuilder(); File xmlFile = new File("c:\\file.xml"); Document doc = (Document) builder.build(xmlFile); Element rootNode = doc.getRootElement(); // update staff id attribute Element staff = rootNode.getChild("staff"); staff.getAttribute("id").setValue("2"); // add new age element Element age = new Element("age").setText("28"); staff.addContent(age); // update salary value staff.getChild("salary").setText("7000"); // remove firstname element staff.removeChild("firstname"); XMLOutputter xmlOutput = new XMLOutputter(); // display nice nice xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new FileWriter("c:\\file.xml")); // xmlOutput.output(doc, System.out); System.out.println("File updated!"); } catch (IOException io) { io.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } } }
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
Great example. How to add new attribute and element? Thanks!
expected result:
Worked just fine. Thanks
thank you.
Thanks a lot, i spend a long time trying to get my xml modified. With ur code and little modifications i could do it.
This is great! Thank you very much for providing this. As a suggestion perhaps you could include an “add attribute” sample of code to your sample. Thanks again
Ok, thanks for your suggestion, will provide it in future.
Thank you very much for the code. It is very useful for me.
I am facing one problem with this code. The node value is not getting updated, but no error is shown.
below is the code
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public static void main(String argv[]) {
try{
String filepath = “c:\\testing.xml”;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
//Get the root element
Node company;
company = doc.getFirstChild();
//Get the staff element , it may not working if tag has spaces, or
//whatever weird characters in front…it’s better to use
//getElementsByTagName() to get it directly.
//Node staff = company.getFirstChild();
//Get the staff element by tag name directly
Node staff = doc.getElementsByTagName(“staff”).item(0);
//update staff attribute
NamedNodeMap attr = staff.getAttributes();
Node nodeAttr = attr.getNamedItem(“id”);
nodeAttr.setNodeValue(“3″);
//nodeAttr.setTextContent(“2″);
//append a new node to staff
Element age = doc.createElement(“age”);
age.appendChild(doc.createTextNode(“28″));
staff.appendChild(age);
//loop the staff child node
NodeList list = staff.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
String nodeName = node.getNodeName();
//get the salary element, and update the value
if(nodeName.equals("salary"))
{
node.setNodeValue("2000000".toString());
System.out.println("Nodevalue:" + node.getNodeValue());
}
}
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(TransformerException tfe){
tfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(SAXException sae){
sae.printStackTrace();
}
}
Thank you in advance for your help.
hi thanks i executed your code it is working fine.
Hi
I got one requirement where I have am geeting the XSD.I have to use xmlbean(for pojo class) and save the data by using Hibernate.I am new to both XMLbean and Hibernate.Please share any sample code based on xsd and xmlbean and hibernate.
Thanks in Advance
I got headache with xml update and I found ur codes.
Its work well and I wanna say thank you to u.
I really appreciate for your codes.
Thank you so much!
Best Regards,
kntsoe
thanks a lot you helped me!!
Thanks used this with WordML horibble markup! But this simplified the XML side, cheers
THX A LOT.. your code helpd us a lot
I tried the above example it’s working fine, could you please help me to create node.
Thanks in advance
Linda
please help me to create node using the the same code
Thanks in advance
Linda
I tried a billion times but it is not actually getting the file.
My filename is Study.xml and my path is D:\\Study.xml but still not working…
Can any one help please???
What’s the error message?
[...] Modify XML file Example to modify XML attribute and element value. [...]
XML File one more time (got escaped in the post):
<?xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?>
<company>
<staff id=”1″>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
</company>
(if this didn’t work, its just the same as the original)
Go through some testing, the Node staff = company.getFirstChild(); may not is a good choice for xml parse work, it seem not working if the xml tag has spaces, or whatever weird characters in front of it…
it’s better to use getElementsByTagName() to get it directly.
Article updated, hope help.
Works like a charm! Thanks alot
XML File:
yong
mook kim
mkyong
100000
—————————
JAVA FILE:
Current Output:
java.lang.NullPointerException
at device.model.ModifyXMLFile.main(ModifyXMLFile.java:56)
yong
mook kim
mkyong
100000
Line 56 is the error, where we try to modify the XML attribute text contents… any help is VERY appreciated!
This example doesn’t seem to work for me… I’m getting the following errors:
java.lang.NullPointerException
at device.model.ModifyXMLFile.main(ModifyXMLFile.java:45)
This error occurs on the line which looks for an “id” attribute in the Staff XML. After commenting out the attribute re-writing code, I still get:
Exception in thread “main” org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
at com.sun.org.apache.xerces.internal.dom.NodeImpl.insertBefore(NodeImpl.java:478)
at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(NodeImpl.java:235)
at device.model.ModifyXMLFile.main(ModifyXMLFile.java:51)
Java Result: 1
Seems odd I can’t get this basic example working, might make more sense to finally switch from traditional SAX/DOM to the much faster and easier to troubleshoot VTD-XML
I’m just tested this example, it’s working fine for me? Would you mind to send me your XML and Java files to me?