使用dom4j来解析一个xml文件。 核心代码:

		File xmlFile = new File(file);
		SAXReader reader = new SAXReader();
		Document doc = reader.read(xmlFile);

		Element root = doc.getRootElement();
		Iterator itRoot = root.elements().iterator();

先返回root元素,然后再使用Iterator迭代出来。 根据层级关系来迭代。 这是一个示例,公供参考:

package name.frb.xml;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlDemo {
	public static void main(String args[]) throws DocumentException {
		String file = "src/main/java/frb.xml";
		listXmlElements(file);
	}

	private static void listXmlElements(String file) throws DocumentException {
		File xmlFile = new File(file);
		SAXReader reader = new SAXReader();
		Document doc = reader.read(xmlFile);

		Element root = doc.getRootElement();
		Iterator itRoot = root.elements().iterator();
		while (itRoot.hasNext()) {
			Element channel = (Element) itRoot.next();
			System.out.println(channel.elementText("title"));
			System.out.println(channel.elementText("link"));
			System.out.println(channel.elementText("description"));
			System.out.println(channel.elementText("lastBuildDate"));
			System.out.println(channel.elementText("docs"));
			System.out.println(channel.elementText("language"));

			Iterator itItem = channel.elements().iterator();
			if (itItem != null) {
				while (itItem.hasNext()) {
					Element item = (Element) itItem.next();
					String title = item.elementText("title");
					String link = item.elementText("link");
					if (title != null) {
						System.out.println(title.trim());
					}
					if (link != null) {
						System.out.println(link.trim());
					}
				}
			}
		}
	}
}


Published

18 December 2012