import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.util.List;
public class TestDamo {
public static void main(String[] args) throws DocumentException {
//创建核心解析器对象
SAXReader saxReader = new SAXReader();
//解析xml文件生成一个document对象
Document document = saxReader.read(TestDamo.class.getClassLoader().getResourceAsStream("books.xml"));
//获得根元素books
Element rootElement = document.getRootElement();
//获得根元素下面所有子元素book
List<Element> elements = rootElement.elements("book");
//遍历book集合,获得单个book
for (Element element : elements) {
//获取book的id属性
String id = element.attributeValue("id");
System.out.println("id : " + id);
//获取book下的所有子元素 name,author,sale
List<Element> listElem = element.elements();
//遍历集合 获取每一个子元素
for (Element elem : listElem) {
//元素名
String name = elem.getName();
//文本值
String text = elem.getText();
System.out.println("--- " + name + " : " + text);
}
}
}
}
转载于:https://www.cnblogs.com/otways/p/9845865.html