xml不是要来取代html的,是对html的补充,用来与html协同工作的语言。
xml 的主要作用有:
1、用来保存数据,而且这些数据具有自我描述性。
2、它还可以做为项目或者模块的配置文件。
3、还可以做为网络传输数据的格式(现在 JSON 为主)。
xml 语法:
1. 文档声明。
2. 元素(标签)。
3. xml 属性。
4. xml 注释。
5. 文本区域(CDATA 区)。
xml 属性:
xml 的标签属性和 html 的标签属性是非常类似的,属性可以提供元素的额外信息,
在标签上可以书写属性, 一个标签上可以书写多个属性。每个属性的值必须使用 引号引起来。
属性书写的规则和标签的书写规则一致。
语法规则:
1.所有 XML 元素都须有关闭标签(也就是闭合)。
2.XML 标签对大小写敏感。
3.XML 必须正确地嵌套。
4.XML 文档必须有根元素。
5.XML 的属性值须加引号。
6.CDATA 语法可以告诉 xml 解析器,我CDATA 里的文本内容,只是纯文本,不需要 xml 语法解析。
CDATA 格式: <![CDATA[输入的字符]]>。
xml 解析:
dom4j 解析技术:
将jar包添加到内路径
XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book sn="SN12341232">
<name>book1</name>
<price>9.9</price>
<author>author1</author>
</book>
<book sn="SN12341231">
<name>book2</name>
<price>99.99</price>
<author>author2</author>
</book>
</books>
创建Book类:
public class Book {
private String sn;
private String name;
private BigDecimal price;
private String author;
public Book(String sn, String name, BigDecimal price, String author) {
this.sn = sn;
this.name = name;
this.price = price;
this.author = author;
}
public Book() {
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book{" +
"sn='" + sn + '\'' +
", name='" + name + '\'' +
", price=" + price +
", author='" + author + '\'' +
'}';
}
}
创建Dom4jTest类:
public class Dom4jTest {
@Test
public void test1() throws Exception {
// 创建一个SaxReader输入流,去读取 xml配置文件,生成Document对象
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("05_xml/src/books.xml");
System.out.println(document);
}
@Test
public void test2(){
//1.读取books.xml文件
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/books.xml");
//2.通过Document对象获取根元素
Element root = document.getRootElement();
//3.通过根元素获取book标签对象
List<Element> books= root.elements("book");
//4.遍历
for (Element book : books){
Element name = book.element("name");
//获取标签文本
String nameText = name.getText();
//直接获取指定标签的文本内容
String priceText = book.elementText("price");
String authorText = book.elementText("author");
String snValue = book.elementText("sn");
System.out.println(new Book(snValue,nameText,Double.parseDouble(priceText)));
}
}
}