CDATA格式
不会被xml解析
<![CDATA[
]]>
Dom4j解析
-
新建Java工程,创建lib文件夹,将dom4j包添加
https://wwa.lanzous.com/iSdbAowne4h
解压-选择dom4j.jar文件放到lib文件夹下 -
导入jar包
File-project structure
-
在src下创建book.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
- 在src下新建一个包,在包下创建一个Book类
package com.ningqian.xml;
import java.math.BigDecimal;
/**
* @author ningqian
* @create -05-07 21:47
*/
public class Book {
private String sn;
private String name;
private BigDecimal price;
private String author;
public Book() {
}
public Book(String sn, String name, BigDecimal price, String author) {
this.sn = sn;
this.name = name;
this.price = price;
this.author = author;
}
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 testDom4j() throws DocumentException {
SAXReader saxReader = new SAXReader();
//读取xml文件
Document document = saxReader.read("src/book.xml");
//通过Document对象获取根元素
Element rootElement = document.getRootElement();
//通过根元素获取book标签对象
List<Element> books = rootElement.elements("book");
for(Element book:books){
//asXML():将标签对象转成标签字符串
//System.out.println(book.asXML());
Element bookName = book.element("name");
//getText()可以获取标签内的文本内容
String bookNameText = bookName.getText();
//elementText()直接获取标签的内容
String bookPriceText = book.elementText("price");
String bookAuthorText = book.elementText("author");
String bookSn = book.attributeValue("sn");
System.out.println(new Book(bookSn,bookNameText,new BigDecimal(bookPriceText),bookAuthorText));
}
}
}
- 测试结果