Java & amp; Xml tutorial (7) Use JDOM to modify XML file content

Source: Internet
Author: User

Java & Xml tutorial (7) Use JDOM to modify XML file content

JDOM provides a flexible way to operate XML files. It is very simple to use JDOM and the code is concise and readable. We have learned how to use JDOM to parse XML files. This section describes how to use JDOM to modify XML file content.
In this tutorial, we are going to modify the following XML file:
Employees. xml

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><employees xmlns="http://www.journaldev.com/employees">  <employee id="1">    <age>25</age>    <name>Pankaj</name>    <gender>Male</gender>    <role>Java Developer</role>  </employee>  <employee id="2">    <age>34</age>    <name>Mona</name>    <gender>Female</gender>    <role>Manager</role>  </employee>  <employee id="3">    <age>45</age>    <name>Dave</name>    <gender>Male</gender>    <role>Support</role>  </employee></employees></code>

We will change each Employee element in xml:
1. modify all the name elements to make all the content in uppercase.
2. After gender (gender) is Male (Male)'s id attribute value, append M, gender (gender) is Female (Female)'s id attribute value, and append F.
3. Delete the gender element.
4. Add a salary (salary) sub-element for each Employee element. The default value is 1000.
The following is the program code:
JDOMXMLEditor. java

package com.journaldev.xml.jdom;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.util.List;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.Namespace;import org.jdom2.input.SAXBuilder;import org.jdom2.output.Format;import org.jdom2.output.XMLOutputter;public class JDOMXMLEditor {    public static void main(String[] args) throws JDOMException, IOException {        final Namespace ns = Namespace.getNamespace("http://www.journaldev.com/employees");        //Get the JDOM document        org.jdom2.Document doc = useSAXParser("employees.xml");        //Get list of Employee element        Element rootElement = doc.getRootElement();        List
  
    listEmpElement = rootElement.getChildren("Employee", ns);        //loop through to edit every Employee element        for (Element empElement : listEmpElement) {            //change the name to BLOCK letters            String name = empElement.getChildText("name", ns);            if (name != null)                empElement.getChild("name", ns).setText(name.toUpperCase());            //edit the ID attribute based on Gender            String gender = empElement.getChildText("gender", ns);            if (gender != null && gender.equalsIgnoreCase("female")) {                String id = empElement.getAttributeValue("id");                empElement.getAttribute("id").setValue(id + "F");            } else {                String id = empElement.getAttributeValue("id");                empElement.getAttribute("id").setValue(id + "M");            }            //remove gender element as it's not needed anymore            empElement.removeChild("gender", ns);            //add salary element with default value to every employee            empElement.addContent(new Element("salary", ns).setText("1000"));        }        //document is processed and edited successfully, lets save it in new file        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());        //output xml to console for debugging        //xmlOutputter.output(doc, System.out);        xmlOutputter.output(doc, new FileOutputStream("employees_new.xml"));    }    //Get JDOM document from SAX Parser    private static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,            IOException {        SAXBuilder saxBuilder = new SAXBuilder();        return saxBuilder.build(new File(fileName));    }}
  

Note that the above Code uses the namespace to get all elements and the running program outputs the XML file content:
Employees_new.xml

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><employees xmlns="http://www.journaldev.com/employees">  <employee id="1M">    <age>25</age>    <name>PANKAJ</name>    <role>Java Developer</role>    <salary>1000</salary>  </employee>  <employee id="2F">    <age>34</age>    <name>MONA</name>    <role>Manager</role>    <salary>1000</salary>  </employee>  <employee id="3M">    <age>45</age>    <name>DAVE</name>    <role>Support</role>    <salary>1000</salary>  </employee></employees></code>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.