一、何为xml
定义
XML是可扩展性标记语言,类似于html,有属于自己的标签等元素,其主要的作用如下
- 1、用来保存数据,而且这些数据具有自我描述性
- 2、它可以作为项目或者模块的配置文件
- 3、还可以作为网络传输数据的格式(现在以json为主)
语法
- 文档声明
- 元素(标签)
- xml属性
- xml注释
- 文本区域(CDATA区)
示例如下:
在这里插入代码片
<?xml version="1.0" encoding="UTF-8" ?>
<!--以上内容就是xml文件的声明
version="1.0"-->
<books>
<book sn="SN12341232">
<name>辟邪剑谱</name>
<price>9.9</price>
<author>小雷</author>
</book>
<book sn="SN12341231">
<name>葵花宝典</name>
<price>99.99</price>
<author>小马</author>
</book>
</books>
二、如何读取xml
主要依赖的包有dom4j-1.6.1.jar
下面以上面的示例代码来进行读取
定义bean类作为
package com.coderp.mapper;
/**
* @program: 06-xml
* @description:
* @author: CoderP
* @create: 2021-04-26 08:59
**/
public class Books {
private String name;
private Double price;
private String author;
private String sn;
public Books(String name, Double price, String author, String sn) {
this.name = name;
this.price = price;
this.author = author;
this.sn = sn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
@Override
public String toString() {
return "Books{" +
"name='" + name + '\'' +
", price=" + price +
", author='" + author + '\'' +
", sn='" + sn + '\'' +
'}';
}
}
读取和遍历类
package com.coderp.mapper;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
/**
* @program: 06-xml
* @description: 读取xml
* @author: CoderP
* @create: 2021-04-26 09:19
**/
public class XmlReader {
@Test
public void test() {
System.out.println("您好");
}
//获取document对象
@Test
public void getDocument() throws Exception {
SAXReader saxReader=new SAXReader();
//读取方式1
//Document document=saxReader.read("../bookswe.xml");
//读取方式1
Document document=saxReader.read("bookswe.xml");
System.out.println(document);
}
//遍历标签
@Test
public void printElement() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read("bookswe.xml");
Element root=document.getRootElement();
List<Element> books=root.elements("book");
for (Element book : books) {
Element nameElement=book.element("name");
Element priceElement=book.element("price");
Element authorElement=book.element("author");
System.out.println("书名 "+nameElement.getText()+", 价格:"
+priceElement.getText()+", 作者"+authorElement.getText());
}
}
}