XML简介

1. 什么是XML

请先下载附录中的dom4j文件

2. XML格式

3. XML标签

4. XML编写注意事项

5. 转义符⭐

6. 解析XML

7. 常用接口介绍

8. 访问DOM树节点

9. 保存XML文件

10. 范例代码:包含(显示/添加/删除/修改)

XML文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<scoreInfo>
    <sport name="王贤明" id="1001">
        <expectScore>预计得分75</expectScore>
        <realScore>实际得分80</realScore>
    </sport>

    <sport name="宋佳" id="1002">
        <expectScore>预计得分75</expectScore>
        <realScore>实际得分88</realScore>
    </sport>
</scoreInfo>

应用代码

复制代码
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

public class dom4jParse {
    private Document doc;

    /**
     * 加载文件转换成dom4j的文档对象
     */
    public void loadDocument() throws DocumentException {
        //读取xml文件的对象
        SAXReader saxReader = new SAXReader();
        //读取文件, 将读取的内容转换成document对象
        doc = saxReader.read("src/c05/score.xml");
    }


    //将添加/删除/修改操作写入XML文件==========================================
    public void addScoreInfo() throws IOException {
        //创建xml格式的Output对象
        OutputFormat outputFormat = new OutputFormat();
        //创建文件写入的对象
        FileWriter fileWriter = new FileWriter("src/c05/score.xml");
        //将文件写入的格式转换为xml格式
        XMLWriter xmlWriter = new XMLWriter(fileWriter,outputFormat);
        //写入文件doc
        xmlWriter.write(doc);
        //关闭流
        xmlWriter.close();
        fileWriter.close();
    }

    /**
     * 获取xml文件中存储的数据
     */
    public void show(){
        //获取根节点
        Element root = doc.getRootElement();
        System.out.println("根节点:"+root.getName());
        System.out.println("=====================================");
        //根元素下有多个子元素
        Iterator<Element> it = root.elementIterator();
        while (it.hasNext()){
            //获取第i个元素<sport>
            Element sport = it.next();
            System.out.println("元素名称:"+sport.getName());
            //获取id 和name的属性值
            String name = sport.attributeValue("name");
            String id = sport.attributeValue("id");
            System.out.println("运动员:"+name+",ID:"+id);
            //获取<expectScore> 和 <realScore>元素值
            Element expectScoreElement = sport.element("expectScore");
            Element realScoreElement = sport.element("realScore");
            //获取<expectScore> 和 <realScore>元素里的文本
            String expectScore = expectScoreElement.getText();
            String realScore = realScoreElement.getText();
            System.out.println(expectScore+","+realScore);
            System.out.println("=====================================");

        }
    }

    //添加XML文件中的元素==========================================
    public void addSport() throws IOException {
        //获取根节点
        Element root = doc.getRootElement();
        //添加子元素和子元素的属性
        Element sportElement = root.addElement("sport");
        sportElement.addAttribute("name","张三");
        sportElement.addAttribute("id","1003");
        //添加子元素的元素<expectScore>、<realScore>和<expectScore>、<realScore>元素内的文本信息
        Element expectScoreElement = sportElement.addElement("expectScore");
        expectScoreElement.setText("预计得分70");
        Element realScoreElement = sportElement.addElement("realScore");
        realScoreElement.setText("实际得分95");
        //调用写入方法
        addScoreInfo();
    }

    //删除XML文件中的元素==========================================
    public void deleteSport() throws IOException {
        //获取根节点
        Element root = doc.getRootElement();
        //根元素下有多个子元素
        Iterator<Element> it = root.elementIterator();
        while (it.hasNext()) {
            Element sportElement=it.next();
            //获取属性id为1003的子元素
            String id=sportElement.attributeValue("id");
            if (id.equals("1003")){
                //删除根节点下的该元素
                root.remove(sportElement);
            }
        }
        //调用写入方法
        addScoreInfo();
    }

    //修改XML文件中的元素==========================================
    public void modifySport() throws IOException {
        //获取根节点
        Element root = doc.getRootElement();
        //根元素下有多个子元素
        Iterator<Element> it = root.elementIterator();
        while (it.hasNext()) {
            Element sportElement=it.next();
            //获取属性id为1003的子元素
            String id=sportElement.attributeValue("id");
            if (id.equals("1003")){
                //获取子元素的元素<expectScore>、<realScore>,将<expectScore>、<realScore>元素内的文本信息替换
                Element expectScoreElement = sportElement.element("expectScore");
                expectScoreElement.setText("预计得分60");
                Element realScoreElement = sportElement.element("realScore");
                realScoreElement.setText("实际得分70");
            }
        }
        //调用写入方法
        addScoreInfo();
    }
}

1. 显示

复制代码
import org.dom4j.DocumentException;

import java.io.IOException;

public class TestScore {
    public static void main(String[] args) throws DocumentException, IOException {
        dom4jParse dom4jParse = new dom4jParse();
        dom4jParse.loadDocument();
        dom4jParse.show();
    }
}

运行结果:

2. 添加

添加一个元素,姓名张三,ID1003,预计得分70,实际得分95

复制代码
import org.dom4j.DocumentException;

import java.io.IOException;

public class TestScore {
    public static void main(String[] args) throws DocumentException, IOException {
        dom4jParse dom4jParse = new dom4jParse();
        dom4jParse.loadDocument();
        dom4jParse.addSport();
        dom4jParse.show();
    }
}

运行结果:

在XML文件中:

3. 删除

根据1003这个ID来删除这个元素

复制代码
import org.dom4j.DocumentException;

import java.io.IOException;

public class TestScore {
    public static void main(String[] args) throws DocumentException, IOException {
        dom4jParse dom4jParse = new dom4jParse();
        dom4jParse.loadDocument();
        dom4jParse.deleteSport();
        dom4jParse.show();
    }
}

运行结果:

在XML文件中:

4. 修改

根据1003这个ID来修改预计得分为60,实际得分为70

复制代码
import org.dom4j.DocumentException;

import java.io.IOException;

public class TestScore {
    public static void main(String[] args) throws DocumentException, IOException {
        dom4jParse dom4jParse = new dom4jParse();
        dom4jParse.loadDocument();
        dom4jParse.modifySport();
        dom4jParse.show();
    }
}

显示结果:

在XML文件中:

看完范例代码以后,可以看到其中添加删除修改的元素都是直接以字符串的形式出现了,那么如果只有对象没有XML文件,要我们自己生成XML文件并将对象的元素插入其中,那么我们该如何实现呢?课后练习中我们会将代码展示出来。

附录⭐:

使用dom4j版本:dom4j-1.6.1.jar

https://download.csdn.net/download/m0_62696265/90707510?spm=1001.2014.3001.5503

如无法下载,请自行通过科学方式下载

课后练习:

面向对象的XML综合练习-CSDN博客

相关推荐
leikooo4 小时前
用餐厅和盘子理解栈和堆
java·数据结构·链表·rust
Ivanqhz6 小时前
激活函数在 Transformer 中的作用及各种变体简述
java·linux·数据库·人工智能·深度学习
沙漠之主6 小时前
C++编程教学设计资料:从入门到实战的完整课程方案
java·前端·c++
hasty6 小时前
不上传新包,也能改变用户拿到的版本:npm dist-tag 的 OIDC 权限治理
前端·npm·node.js
FPGA小徐6 小时前
PA1 基础设施(2)深度解析:NEMU 中 ITRACE、MTRACE、FTRACE、IRINGBUF、ETRACE、DIFFTEST 全解析
java·服务器·网络
Csvn7 小时前
diff 算法(虚拟 DOM Reconciliation)
前端
YOLO数据集集合7 小时前
EvoAgent:面向PR研发治理的自进化Multi-Agent Harness系统
java·开发语言·目标检测·agent·自进化
知行EDI7 小时前
知行之桥 MaBang 端口使用指南——Create Order 订单创建篇
java·服务器·数据库
笑鸿的学习笔记7 小时前
C++笔记之大块顺序写
java·c++·笔记
打工仔折腾 AI7 小时前
从 Demo 到生产级 Agent:8 个关键设计机制与 Python 实现拆解
java·jvm·人工智能·后端·python·langchain·ai agent 实战