Search code examples
javaxmljdom

How to change values of inner node of a xml using jdom in java


I have tried changing xml values with the help of jdom by referring this link - http://www.mkyong.com/java/how-to-modify-xml-file-in-java-jdom/

xml shown in the sample:

<?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>

The thing i am not clear that how to handle the following xml scenario:

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff>
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>
        <basic>1000</basic>
        <hra>150</hra>
   </salary>
  </staff>
  <staff>
    <firstname>sanjay</firstname>
    <lastname>machani</lastname>
    <nickname>chong</nickname>
    <salary>
        <basic>2000</basic>
        <hra>200</hra>
   </salary>
  </staff>
</company>

My staff tag won't be having id and also i would be having child tags for salary. But i need to change salary for sanjay(firstname) in xml using java.

Any suggestions would be helpful.


Solution

  • If you are using JDOM you can iterate through the elements with this:

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.List;
    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 yourClass{
        public static void main(String[] args) {
    
            File xml = new File("yourFile.xml");
            try {
                Document doc = (Document) new SAXBuilder().build(xml);
                Element rootNode = doc.getRootElement();
                List list = rootNode.getChildren("staff");
                XMLOutputter xmlOut = new XMLOutputter();
    
                for (int i = 0; i < list.size(); i++) {
    
                    Element node = (Element) list.get(i);
                    if (node.getChildText("firstname").equals("sanjay"))
                        node.getChild("salary").getChild("basic").setText("250000");
                    xmlOut.setFormat(Format.getPrettyFormat());
                    xmlOut.output(doc, new FileWriter("yourFile.xml"));
                }
            } catch (IOException io) {
                System.out.println(io.getMessage());
            } catch (JDOMException jdomex) {
                System.out.println(jdomex.getMessage());
            }
        }
    
    }