Java&Xml Tutorial (7) Using JDOM to modify the content of XML files

黄舟
Release: 2017-02-22 14:51:35
Original
1892 people have browsed it

JDOM provides a very flexible way to operate XML files. Using JDOM is very simple and the code is concise and readable. Earlier we learned how to use JDOM to parse XML files. This section introduces how to use JDOM to modify the content of XML files.

In this tutorial, we are going to modify the following XML file:
employees.xml

<?xml version="1.0" encoding="UTF-8"?><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>
Copy after login
Copy after login

We will change each Employee element in the xml:
1. Modify all name elements so that their contents become all uppercase.
2. Append M after the id attribute value where gender is Male, and append F after the id attribute value when gender is Female.
3. Delete the gender element.
4. Add salary (salary) sub-element to 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<Element> 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&#39;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));
    }

}
Copy after login

It should be noted that the above code uses the namespace to obtain all elements, and the running program outputs the XML file content:
employees_new.xml

<?xml version="1.0" encoding="UTF-8"?><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>
Copy after login
Copy after login

JDOM provides a very flexible way to operate XML files. Using JDOM is very simple and the code is concise and readable. Earlier we learned how to use JDOM to parse XML files. This section introduces how to use JDOM to modify the content of XML files.
In this tutorial, we are going to modify the following XML file:
employees.xml

<?xml version="1.0" encoding="UTF-8"?><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>
Copy after login
Copy after login

We will change each Employee element in the xml:
1. Modify all name elements , making its content all uppercase.
2. Append M after the id attribute value where gender is Male, and append F after the id attribute value when gender is Female.
3. Delete the gender element.
4. Add salary (salary) sub-element to 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<Element> 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&#39;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));
    }

}
Copy after login

It should be noted that the above code uses the namespace to obtain all elements, and the running program outputs the XML file content:
employees_new.xml

<?xml version="1.0" encoding="UTF-8"?><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>
Copy after login
Copy after login

The above is the Java&Xml tutorial (7) using JDOM to modify the content of XML files. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template