搜索
首页后端开发XML/RSS教程Java&Xml教程(七)使用JDOM修改XML文件内容

JDOM提供了非常灵活的方式操作XML文件,使用JDOM非常简单而且代码简洁可读性强。前面我们学习了如何使用JDOM解析XML文件,本节介绍如何使用JDOM修改XML文件内容。 

在这个教程中,我们准备对下面的XML文件进行修改:
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>

我们将改变xml中每个Employee元素:
1.修改所有name元素,使它的内容全部变成大写。
2.在gender(性别)为Male(男)的id属性值后追加M,gender(性别)为Female(女) 的id属性值后追加F。
3.删除gender元素。
4.为每个Employee元素增加salary(薪水)子元素,默认值为1000。
下面是程序代码:
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));
    }

}

需要注意的是上面代码使用命名空间获取所有元素,运行程序输出XML文件内容:
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>

JDOM提供了非常灵活的方式操作XML文件,使用JDOM非常简单而且代码简洁可读性强。前面我们学习了如何使用JDOM解析XML文件,本节介绍如何使用JDOM修改XML文件内容。
在这个教程中,我们准备对下面的XML文件进行修改:
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>

我们将改变xml中每个Employee元素:
1.修改所有name元素,使它的内容全部变成大写。
2.在gender(性别)为Male(男)的id属性值后追加M,gender(性别)为Female(女) 的id属性值后追加F。
3.删除gender元素。
4.为每个Employee元素增加salary(薪水)子元素,默认值为1000。
下面是程序代码:
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));
    }

}

需要注意的是上面代码使用命名空间获取所有元素,运行程序输出XML文件内容:
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>

以上就是Java&Xml教程(七)使用JDOM修改XML文件内容的内容,更多相关内容请关注PHP中文网(www.php.cn)!


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
python怎么读取xml文件python怎么读取xml文件May 16, 2025 am 11:09 AM

用Python读取XML文件的方法包括:1.使用xml.etree.ElementTree库进行基本解析;2.使用lxml库和XPath表达式进行高级解析。通过这些方法,可以高效地处理和提取XML文件中的数据。

xml 怎么转换成表格xml 怎么转换成表格May 16, 2025 am 11:06 AM

将XML数据转换成表格可以通过以下步骤实现:1.解析XML文件,2.将数据映射到表格结构,3.生成表格数据。使用Python的xml.etree.ElementTree和pandas库可以轻松实现这一转换过程。

xml怎么格式化文件xml怎么格式化文件May 16, 2025 am 11:03 AM

格式化XML文件的原因是提高人类的阅读和维护效率。1.手动格式化效率低且易出错。2.自动化工具如Notepad 和VisualStudioCode能快速整理XML文件。3.使用Python的xml.dom.minidom模块可以简单格式化XML字符串,但需注意可能添加额外空白节点。

xml视须文件怎么打开xml视须文件怎么打开May 16, 2025 am 11:00 AM

.xsm文件是一种XMLSchema文件,用于定义XML文件的结构和约束。1)使用文本编辑器如Notepad 或VisualStudioCode打开.xsm文件。2)对于高级功能,使用OxygenXMLEditor或AltovaXMLSpy进行Schema验证和自动补全。3)通过Python的lxml库,可以验证XML文件是否符合Schema,并使用流式处理优化大型文件的处理性能。

微信中发送的xml怎么打开微信中发送的xml怎么打开May 16, 2025 am 10:57 AM

微信中发送的XML文件可以通过以下步骤打开和处理:1.从微信中提取XML文件:长按文件,选择“保存到手机”或“下载”。2.在不同设备上打开文件:在Windows上使用浏览器或Notepad ,在Mac上使用浏览器或TextEdit,在iOS上使用“文件”应用,在Android上使用“文件管理器”或XML查看器应用。3.理解和使用XML文件内容:通过浏览器或文本编辑器查看文件内容,必要时使用编程语言如Python进行解析和修改。

xml文件是什么怎么操作xml文件是什么怎么操作May 16, 2025 am 10:54 AM

XML文件的核心作用是存储和传输结构化数据。1)解析XML文件可使用DOM或SAX方法,DOM适合小文件,SAX适合大文件。2)生成XML文件可通过DOM或直接编写。3)处理命名空间时,使用命名空间前缀避免标签冲突。4)调试时,使用验证工具和异常处理。5)优化时,使用SAX解析器和缓存机制。

xlsx怎么转换成xmlxlsx怎么转换成xmlMay 16, 2025 am 10:51 AM

使用Python可以将xlsx文件转换为xml文件。1)使用openpyxl库读取xlsx文件,2)使用xml.etree.ElementTree库创建和写入xml文件,3)遍历xlsx文件中的数据并填充到xml结构中,4)处理可能遇到的编码、数据类型和缺失值问题。

发票怎么转换成xml发票怎么转换成xmlMay 16, 2025 am 10:48 AM

将发票转换成XML格式可以通过以下步骤实现:1.数据解析:从发票中提取相关信息。2.数据映射:将提取的数据映射到XML结构中。3.XML生成:使用Python的xml.etree.ElementTree模块生成XML文件,这一过程包括逐步构建XML树结构并写入文件。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。