Home Backend Development XML/RSS Tutorial Java&Xml Tutorial (7) Using JDOM to modify the content of XML files

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

Feb 22, 2017 pm 02:51 PM

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Java Program to insert an element at the Bottom of a Stack Java Program to insert an element at the Bottom of a Stack Feb 07, 2025 am 11:59 AM

A stack is a data structure that follows the LIFO (Last In, First Out) principle. In other words, The last element we add to a stack is the first one to be removed. When we add (or push) elements to a stack, they are placed on top; i.e. above all the

See all articles