1.dom4j解析技术
package com.donggei.pojo;
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;
/**
* @className: Dom4jTest
* @description: TODO 类描述
* @author: Dong
* @date: 2022/2/4
**/
public class Dom4jTest {
@Test
public void test1() throws DocumentException {
//创建一个SaxReader输入流,去读取xml配置文件,生成bocument对象
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/books.xml");
System.out.println(document);
}
@Test
public void test2() throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read("src/books.xml");
//通过根元素获取book标签对象
Element rootElement = document.getRootElement();
// System.out.println(rootElement);
List<Element> books = rootElement.elements("book");
for (Element book : books) {
//asXML 把标签对象,转化成标签字符串
//System.out.println(book.asXML());
Element nameElement = book.element("name");
//System.out.println(nameElement.asXML());
//<name>java编程思想</name>
//<name>葵花宝典</name>
// getText();可T以获取标签中的文本内容
String nameElementText = nameElement.getText();
//System.out.println(nameElementText);
//java编程思想
//葵花宝典
//直接获取指定标签名的文本内容
String price = book.elementText("price");
System.out.println(price);
String author = book.elementText("author");
//获取属性值
String sn = book.attributeValue("sn");
Book book1 = new Book(sn, nameElementText, author, new BigDecimal(price));
System.out.println(book1);
//Book{sn='null', name='java编程思想', author='华仔', price=9.9}
//Book{sn='null', name='葵花宝典', author='班长', price=5.5}
}
}
}
tip:使用了junit单元测试框架,教程