一、基本概念
-
xml元素:
元素是指从开始标签到结束标签的内容 -
xml文档必须有根元素
-
这个符号里面的不会被解析
<![CDATA[
]]>
二、xml解析
两种xml解析技术,DOM和Sax(过时)
第三方解析: jdom在dom基础上进行封装,dom4j又进行封装,puu主要用在Android
三、Dom4j类库的使用–进行xml解析
<books>
<book sn="SN12341232">
<name>book1</name>
<price>9.9</price>
<author>班主任</author>
</book>
<book sn="SN12341231">
<name>book2</name>
<price>99.99</price>
<author>班长</author>
</book>
</books>
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
public class Dom4jTest {
@Test
public void test1() throws DocumentException {
//创建一个SaxReader输入流,去读取xml配置文件,生成Document对象
SAXReader saxReader=new SAXReader();
Document document=saxReader.read("src/books.xml");
System.out.println(document);
}
@Test
public void test2 () throws Exception
{
//1. 读取books.xml文件
SAXReader reader=new SAXReader();
Document document=reader.read("src/books.xml");//注意:在Junit测试中,相对路径时从模块名开始算
//2. 通过document对象获取根元素
Element rootElement = document.getRootElement();
System.out.println(rootElement);
//3. 通过根元素获取book标签对象
//element()和elements()都是通过标签名查找子元素
List<Element> books = rootElement.elements("book");
//4. 遍历,处理每个book标签转换为Book类
for(Element book:books)
{
//asXML 把标签对象转换为标签字符串
//System.out.println(book.asXML());
Element nameElement=book.element("name");
//getText 获取标签中的文本内容
String nameText=nameElement.getText();
// 直接获取指定标签名
String priceText = book.elementText("price"); // Double.parseDouble(priceText) String->double
String authorText=book.elementText("author");
String snValue=book.elementText("sn");
System.out.println(new Book(snValue,nameText,new BigDecimal(priceText),authorText));
}
}
}
import java.math.BigDecimal;
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;
}
}