配置xml文档books:
设计book类:
解析测试代码:
package mypack; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * @auther CodeYourself * @create 2021-07-06-10:29 */ public class myTestMode { List<book>ar=new ArrayList<>(); @Test public void test1()throws Exception{ //创建xml读取流SAXReader对象 SAXReader sr=new SAXReader(); //读取xml文件获取文档对象 Document dc=sr.read("xml/books.xml"); //获取根元素 Element el=dc.getRootElement(); List<Element> elements = el.elements("book"); for(Element x:elements){ //查找属性 String id=x.attribute("sn").getValue(); //查找内容 String name=x.elementText("name"); String auther=x.elementText("auther"); double price=Double.parseDouble(x.elementText("price")); ar.add(new book(id,name,auther,price)); } for(book x:ar){ System.out.println(x); } } }
解析结果: