首页 > 其他 > 详细

dom4j递归读取struts.xml文件

时间:2015-05-25 22:25:57      阅读:199      评论:0      收藏:0      [点我收藏+]
<pre name="code" class="java">package junitTest;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

public class Xmltest {

	@SuppressWarnings("unchecked")
	@Test
	public void testPrint() throws IOException {
		SAXReader reader = null;
		try {
			reader = new SAXReader();
			Document doc = reader.read("d:/soft/struts.xml");
			if (doc == null) {
				System.out.println("null");
			} else {
				Element root = doc.getRootElement();
				List<Element> list = root.elements();
				this.printElements(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}

	}

	@SuppressWarnings("unchecked")
	private void printElements(List<Element> list) {
		for (Iterator<Element> iter = list.iterator(); iter.hasNext();) {
			Element e = (Element) iter.next();
			System.out.println(e.getName() + "\nText="
					+ (e.getText() == "" ? "null" : e.getText()));
			List<Attribute> attributes = e.attributes();
			for (Iterator<Attribute> itera = attributes.iterator(); itera
					.hasNext();) {
				Attribute attr = (Attribute) itera.next();
				System.out.println("  " + attr.getName() + "="
						+ attr.getValue());
			}
			List<Element> subList = e.elements();

			// 递归该元素的子元素们
			printElements(subList);
		}
	}
}





以上是用junit写的一个利用SaxReader递归读取xml的例子,供大家参考,由于很简单,就不做详细解释了。

dom4j递归读取struts.xml文件

原文:http://blog.csdn.net/skyshowshow/article/details/45978763

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!