赞
踩
1.引入dom4j解析xml文件的jar
2.创建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>
3.创建一个book类,并声明构造方法、get、set方法、toString方法
- package com.atguigu.pojo;
-
- import java.math.BigDecimal;
-
- public class Book {
- private String sn;
- private String name;
- private double price;
- private String author;
-
- public Book() {
- }
-
- public Book(String sn, String name, double 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 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;
- }
-
- @Override
- public String toString() {
- return "Book{" +
- "sn='" + sn + '\'' +
- ", name='" + name + '\'' +
- ", price=" + price +
- ", author='" + author + '\'' +
- '}';
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
4.编写一个解析测试类
- import org.dom4j.Document;
- 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 Exception {
- // 创建一个SaxReader输入流,去读取 xml配置文件,生成Document对象
- SAXReader saxReader = new SAXReader();
-
- Document document = saxReader.read("src/books.xml");
- //通过Document对象获取根元素
- Element rootElement = document.getRootElement();
- //通过根元素获取book标签对象
- //element()(有一个子元素)和elements()(有多个子元素)都是通过标签名查找子元素
- List<Element> books = rootElement.elements("book");
- //遍历,处理每个book标签转化为Book类
- for (Element book : books) {
- //asXML()把标签对象,转化为标签字符串
- Element name = book.element("name");
- //getText()可以获取标签中的文本内容
- String nameText = name.getText();
- System.out.println(nameText);
- //直接获取指定标签名的文本内容
- String price = book.elementText("price");
- String author = book.elementText("author");
- //获取属性值sn
- String sn = book.attributeValue("sn");
- System.out.println(price);
- System.out.println(author);
- System.out.println(sn);
- //转化为Book类并输出
- Book book1 = new Book(sn, nameText, Double.parseDouble(price), author);
- System.out.println(book1 );
-
- }
- }
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。