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

Source: Internet
Author: User
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.

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

 
   
  
       25    
   
    Pankaj
       
   
    Male
       
   
    Java Developer
     
    
  
       34    
   
    Mona
       
   
    Female
       
   
    Manager
     
    
  
       45    
   
    Dave
       
   
    Male
       
   
    Support
     
  
 

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

 
   
  
       25    
   
    PANKAJ
       
   
    Java Developer
       
   
    1000
     
    
  
       34    
   
    MONA
       
   
    Manager
       
   
    1000
     
    
  
       45    
   
    DAVE
       
   
    Support
       
   
    1000
     
  
 

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

 
   
  
       25    
   
    Pankaj
       
   
    Male
       
   
    Java Developer
     
    
  
       34    
   
    Mona
       
   
    Female
       
   
    Manager
     
    
  
       45    
   
    Dave
       
   
    Male
       
   
    Support
     
  
 

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

 
   
  
       25    
   
    PANKAJ
       
   
    Java Developer
       
   
    1000
     
    
  
       34    
   
    MONA
       
   
    Manager
       
   
    1000
     
    
  
       45    
   
    DAVE
       
   
    Support
       
   
    1000
     
  
 

The above is the Java & Xml tutorial (7). use JDOM to modify the content of the XML file. For more information, see PHP Chinese website (www.php1.cn )!

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.