Java Web 从入门到退坑 第五章 XML


Java Web 从入门到退坑 —— 第五章 XML


By -gregPerlinLi-


1. XML 简介

什么是 XML

​ XML 是可拓展的标记性语言(Extensible markup language

XML的作用

​ XML 的主要作用有:

​ 1. 用来保存数据,而且这些数据具有自我描述性

​ 2. 它还可以作为项目或者模块的配置文件

​ 3. 还可以作为网络传输数据的格式(现在以 JSON 为主)

2. XML 语法

​ 1. 文档声明

​ 2. 元素(标签)

​ 3. XML 属性

​ 4. XML 注释

​ 5. 文本区域( CDATA 区)

2.1. 文档声明

XML 文件示例

<?xml version="1.0" encoding="utf-8" ?>
<!--
    <?xml version="1.0" encoding="utf-8 ?>
    The above is the declaration of the XML file
    version="1.0"           the version of the XML
    encoding="utf-8         encoding of XML file itself
-->
<books> <!-- books represents multiple book information -->
    <book sn="SN1335656687935"> <!-- book represents a book information, sn property represents the serial number of a book -->
        <name>A brief history of time</name> <!-- name tag represents to the name of the book -->
        <author>Steven Hawking</author> <!-- author tag represents to the author of the book -->
        <price>49.5</price> <!-- price tag represents to the price of the book -->
    </book>
    <book sn="SN1145141919810">
        <name>Java —— From introduction to abandonment</name>
        <author>gregPerlinLi</author>
        <price>99.99</price>
    </book>
</books>

2.2. XML 注释

​ XML 和 HTML 的注释都是一样的

<!-- This is a note -->

2.3. XML 元素(标签)

2.3.1. 回忆 HTML 元素

​ 格式:<titleName> Encapsulated data </titleName>

​ 单标签:<titleName/> <br/>自结束标签

​ 双标签:<titleName> ...Encapsulated data... <\titleName> <p>开始标签 </p>结束标签

​ 标签名大小写不敏感

​ 标签有属性,有基本属性和事件属性

​ 标签必须正确关闭(闭合)

2.3.2. 什么是 XML 元素

​ XML 元素指的是从(且包括)开始标签直到(且包括)结束标签的部分。

​ 元素可包含其他元素、文本或者两者的混合物,元素也可以

<books>
    <book sn="SN1335656687935">
        <name>A brief history of time</name>
        <author>Steven Hawking</author>
        <price>49.5</price>
    </book>
    <book sn="SN1145141919810">
        <name>Java —— From introduction to abandonment</name>
        <author>gregPerlinLi</author>
        <price>99.99</price>
    </book>
</books>

​ 在上例中,<books><book> 都拥有元素内容,因为它们包含了其他元素,<author> 只有文本内容,因为它仅包含文本。

2.3.3. XML 命名规则

XML 元素必须遵循以下原则:

1. 名称可以含有字母、数字以及其他字符

​ 例如:

<book sn="SN1335656687935"> <!-- book represents a book information, sn property represents the serial number of a book -->
        <name>A brief history of time</name> <!-- name tag represents to the name of the book -->
        <author>Steven Hawking</author> <!-- author tag represents to the author of the book -->
        <price>49.5</price> <!-- price tag represents to the price of the book -->
</book>

​ 2. 名称不能以数字或者标点符号开始

​ 例如:

<1book sn="SN1335656687935"></1book>

3. 名称不能以字符 XML(或者 xmlXml)开始 (其实这个是可以的)

4. 名称不能包含空格

​ 例如:

<bo ok sn="SN1335656687935"></bo ok>

2.3.4. XML中的元素(标签)也分为单标签和双标签:

单标签:

<tagName prop="val" prop="val"... />

双标签:

<tagName prop="val" prop="val"...> Text data or sub tags </tagName>

2.4. XML 属性

​ XML 的标签属性和 HTML 的标签属性是非常类似的,属性可以提供元素的额外信息

​ 在标签上可以书写属性:

​ 一个标签上可以书写多个属性,每个属性必须要用 "" 引起来,规则和标签的书写规则一致。

2.5. 语法规则

​ 1. 所有的 XML 元素必须要有关闭标签(也就是闭合)

​ 2. XML 标签对大小写敏感(与 HTML 不一样)

​ 3. XML 标签必须正确地嵌套

​ 4. XML 文档必须要有根元素

​ 根元素就是顶级元素,即没有父标签的元素,每个 XML 文档中有且只能有唯一一个根元素

​ 5. XML 中的特殊字符(如 <&等)需要用到转译符号(与 HTML 的转译符号一致)详情点击此

2.6. 文本区域(CDATA 区)

CADATA 语法可以告诉 XML 解析器 CDATA 中的文本内容,只是纯文本,不需要 XML 语法解析

CDATA 格式:

<![CDATA[Here, the input character can be displayed as it is, without parsing]]>

3. XML 解析技术介绍

​ XML 可拓展标记语言

​ 不管是 HTML 文件还是 XML 文件它们都是标记型文档,都可以使用 W3C 组织制定的 DOM 技术解析

XML 文档对象模型定义访问和操作 XML 文档的标准方法

DOM 将 XML 文档作为一个树型结构,而树叶则被定义为节点

https://www.runoob.com/images/nodetree.gif

document 对象表示的是整个文档(可以是 XML 文档,也可以是 HTML 文档)

具体教程可点击此

​ 早期的 JDK 为我们提供了两种 XML 解析技术 DOMSAX 简介 (已过时,但我们还是需要知道这两种技术)

DOM 解析技术是 W3C 组织制定的,而所有的编程语言都对这个解析技术使用了自己语言的特点进行实现,而 Java 对 DOM 技术解析标记也做了实现。

​ sum 公司在 JDKS 版本对 DOM 解析技术进行升级:SAXSimple API for XML

SAX 解析,它和 W3C 指定的技术不太一样,它是以类似事件机制通过回调告诉用户当前在解析的内容。它是一行一行地读取 XML 文件进行解析的,不会创建大量的 DOM 对象。所以它在解析的时候,在内存的使用上和性能上都优于 DOM 解析。

​ 第三方解析:

JDOMDOM 的基础上进行了封装

DOM4J 又对 JDOM 进行了封装

PULL 主要用在 Android 手机开发,是在跟 SAX 非常类似的事件机制来解析 XML 文件

DOM4J 是第三方解析技术,需要使用第三方提供的类库才可以解析 XML 文件

4. DOM4J 解析技术(重点)

​ 由于 DOM4J 不是 sum 公司的技术,而属于第三方公司的技术,所以需要使用 DOM4J 就需要到 DOM4J 官网下载 DOM4Jjar 包。

4.1. DOM4J 类库的使用

​ 下载地址:https://dom4j.github.io

4.2. DOM4J 编程步骤

​ 1. 先加载 XML 文件创建 Document 对象

​ 2. 通过 Document 对象拿到根元素对象

​ 3. 通过元素 .elements(tagName); 可以返回一个集合,这个集合里放着所有你指定的标签名的元素对象

​ 4. 找到想要修改、删除的子元素,进行相应的操作

​ 5. 保存到硬盘上

4.3. 获取 document 对象

​ 创建一个 lib 目录,并添加 DOM4Jjar 包,并添加到类路径

​ 需要解析的 Books.xml 文件内容

<?xml version="1.0" encoding="UTF-8" ?>
<books>
    <book sn="SN1335656687935">
        <name>A brief history of time</name>
        <author>Steven Hawking</author>
        <price>49.5</price>
    </book>
    <book sn="SN1145141919810">
        <name>Java —— From introduction to abandonment</name>
        <author><![CDATA[<gregPerlinLi>]]></author>
        <price>99.99</price>
    </book>
    <book sn="SN2344556433423" name="Test" author="gregPerlinLi" price="999.9" />
</books>

​ 获取 Document 对象的代码

​ 1. 先创建 SaxReader 对象。这个对象用于读取 XML 文件,并创建 Document 对象

​ 2. 创建 Book

package com.gregperlinli.pojo;

import java.math.BigDecimal;
/**
 * @author gregperlinli
 */
public class Book &#123;
    private String sn;
    private String name;
    private BigDecimal price;
    private String author;
    public Book(String sn, String name, BigDecimal price, String author) &#123;
        this.sn = sn;
        this.name = name;
        this.price = price;
        this.author = author;
    &#125;
    public Book() &#123;
    &#125;
    public String getSn() &#123;
        return sn;
    &#125;
    public void setSn(String sn) &#123;
        this.sn = sn;
    &#125;
    public String getName() &#123;
        return name;
    &#125;
    public void setName(String name) &#123;
        this.name = name;
    &#125;
    public BigDecimal getPrice() &#123;
        return price;
    &#125;
    public void setPrice(BigDecimal price) &#123;
        this.price = price;
    &#125;
    public String getAuthor() &#123;
        return author;
    &#125;
    public void setAuthor(String author) &#123;
        this.author = author;
    &#125;
    @Override
    public String toString() &#123;
        return "Book&#123;" +
                "sn='" + sn + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", author='" + author + '\'' +
                '&#125;';
    &#125;
&#125;

​ 3. 获取 XML 的文内容到 Book 类中

public void main() throws Exception &#123;
        // 1. read books.xml file
        SAXReader reader = new SAXReader();
        // In JUnit testing, the relative path is calculated from the module name
        Document document = reader.read("src/Books.xml");
        // 2. Get the root element through the document object
        Element rootElement = document.getRootElement();
        System.out.println(rootElement);
        // 3. Get the book tag object through the root element
        // element() and elements() are all look up child elements by tag name
        List<Element> books = rootElement.elements("book");
        // 4. Traversal, processing each book label into a book class
        for ( Element book : books ) &#123;
            // asXML() can convert a label object to a label string
            // System.out.println(book.asXML());
            Element nameElement = book.element("name");
            // getText() can get the text content in the tag
            // String nameText = nameElement.getText();
            // elementText() can get the text content directly
            String nameText = book.elementText("name");
            String authorText = book.elementText("author");
            String priceText = book.elementText("price");
            System.out.println(priceText);
            BigDecimal priceVal = new BigDecimal(priceText);
            String snValue = book.attributeValue("sn");
            Book newBook = new Book(snValue, nameText, priceVal, authorText);
            System.out.println(newBook);
        &#125;
&#125;


文章作者: gregPerlinLi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 gregPerlinLi !
  目录