本文主要是介绍DOM4J学习笔记 --- Java遍历解析XML,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先准备的文本是:
<!-- Edited with XML Spy v2007 (http://www.altova.com)
--><CATALOG><CD><TITLE>Empire Burlesque</TITLE><ARTIST>Bob Dylan</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>Columbia</COMPANY><PRICE>10.90</PRICE><YEAR>1985</YEAR></CD>
</CATALOG>
我们利用 DOM4J 的 SAXReader, 和 Iterator() 遍历解析。
package zetyun;import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.Document;
import java.io.File;
import java.util.Iterator;/*** Created by ryan on 17-7-31.*/
public class Main {public static void main(String[] args){load("./xmlfiles/simple.xml");}public static void load(String fileName){try{SAXReader reader = new SAXReader();Document document = reader.read(new File(fileName));Element root = document.getRootElement();Iterator it = root.elementIterator();while (it.hasNext()) {Element element = (Element) it.next();Iterator eleIt = element.elementIterator();while (eleIt.hasNext()) {Element e = (Element) eleIt.next();System.out.println(e.getName() + ": " + e.getText());}System.out.println();}}catch(Exception e){e.printStackTrace();}}
}
这篇关于DOM4J学习笔记 --- Java遍历解析XML的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!