现在的位置: 首页 > 综合 > 正文

一个完整的遍历案例 Dom4j

2013年08月03日 ⁄ 综合 ⁄ 共 1983字 ⁄ 字号 评论关闭

xml文档:

<?xml version="1.0" encoding="GBK"?> 
<doc> 
    <person id="1" sex="m"> 
        <name>zhangsan</name> 
        <age>32</age> 
        <adds> 
            <add code="home">home add</add> 
            <add code="com">com add</add> 
        </adds> 
    </person> 
    <person id="2" sex="w"> 
        <name>lisi</name> 
        <age>22</age> 
        <adds> 
            <add ID="22" id="23" code="home">home add</add> 
            <add ID="23" id="22" code="com">com add</add> 
            <add id="24" code="com">com add</add> 
        </adds> 
    </person> 
</doc>

遍历代码:

public static void main(String[] args) {
		// TODO Auto-generated method stub
		testparseXMLData("C:/Users/mojia/Desktop/dom4j/person.xml");
	}

	public static void testparseXMLData(String xmlFileName) {
		// TODO Auto-generated method stub
		StringBuffer sb = null;

		Document document = null;
		document = parse2Docment(xmlFileName);

		Element rootElement = document.getRootElement();
		sb = new StringBuffer("------------开始遍历------------------\n");
		sb.append(rootElement.getName() + "\n");

		// 遍历当前元素的子元素
		for (Iterator i_pe = rootElement.elementIterator(); i_pe.hasNext();) {
			// 得到rootElement根元素doc的子元素
			Element e_pe = (Element) i_pe.next();
			sb.append(e_pe.getName() + "\t" + e_pe.attributeValue("id") + "\t"
					+ e_pe.attributeValue("sex") + "\t");
			//得到person的子元素name,age
			String name = e_pe.element("name").getText();
			int age = Integer.parseInt(e_pe.element("age").getText());
			sb.append("name----->"+name+"\t"+"age------>"+age+"\n");
			
			Element e_adds = e_pe.element("adds");
			//遍历当前元素person下面的adds元素
			for(Iterator i_adds=e_adds.elementIterator();i_adds.hasNext();){
				Element e_add = (Element)i_adds.next();
				String code = e_add.attributeValue("code");
				String add = e_add.getTextTrim();
				sb.append("\t\t"+e_add.getName()+":"+"code="+code+ " value=\"" + add + "\"\n");
			}
			sb.append("\n");
		}
		sb.append("--------end--------------");
		System.out.println(sb.toString());
	}

	public static Document parse2Docment(String xmlFilePath) {
		SAXReader reader = new SAXReader();
		Document document = null;
		File f = null;

		try {
			f = new File(xmlFilePath);
			InputStream in = new FileInputStream(f);
			document = reader.read(in);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return document;
	}

抱歉!评论已关闭.