DOM4j解析XML
DOM4j解析XML文件,导入dom4j-1.6.1.jar。
XML文件:
<?xml version="1.0" encoding="utf-8" ?> <books> <book> <name>挪威的森林</name> <author>村上春树</author> <genre>文学</genre> </book> <book> <name>三体</name> <author>刘慈欣</author> <genre>科幻</genre> </book> </books>
解析测试代码:
//book.java为bean文件,属性为name author genre
package com.WebTest; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.junit.Test; import java.util.List; public class DOM4jTest { @Test public void Dom4jTest() throws DocumentException { SAXReader saxReader = new SAXReader(); Document read = saxReader.read("src\\com\\WebTest\\XMLTest.xml"); Element rootElement = read.getRootElement(); List<Element> elements = rootElement.elements("book"); for (Element book : elements) { //方式1 Element name = book.element("name"); String text = name.getText(); //方式2 String author = book.elementText("author"); String genre = book.elementText("genre"); System.out.println(new book(text,genre,author)); } } }