Java XML解析 - 利用DOM4j解析XML实例

直接上代码进行分析,这是最简单实用的方法。

import freemarker.template.Configuration;

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class xmlTest {
	
	private Configuration configure = null;
	
	public xmlTest(){
		 configure= new Configuration();
		 configure.setDefaultEncoding("utf-8");
	}
	
	public static void main(String[] args) {
	
		String string ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + 
				"<root>\r\n" + 
				"<row age=\"25\"><name>崔卫兵</name><college>浙江大学</college><telephone>62354666</telephone><notes>男,1982年生,硕士,现就读于北京邮电大学</notes></row>\r\n" + 
				"<row age=\"25\"><name>王鹏</name><college leader=\"学院领导\">北京大学</college><telephone>62358888</telephone><notes>男,1987年生,硕士,现就读于中国农业大学</notes></row>\r\n" + 
				"<row age=\"45\"><name>王阿道</name> <college leader=\"\">沈阳大学</college><telephone>66666666</telephone><notes>男,1982年生,硕士,现就读于北京邮电大学</notes></row>\r\n" + 
				"<row age=\"35\"><name>刘桂</name><college>上海大学</college><telephone>88888888</telephone><notes>男,1982年生,硕士,现就读于北京邮电大学</notes></row>\r\n" + 
				"</root>";
		try {
			getXmlParsing(string);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	/**
	 * 解析XML
	 * @param xml
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static void getXmlParsing(String xml) throws Exception{
		Document document = null;
		document=DocumentHelper.parseText(xml);
		Element root=document.getRootElement();//根元素
		Iterator iterator=root.elements().iterator();//子元素
		while (iterator.hasNext()) {
			Element rootText=(Element) iterator.next();
			System.out.println("111&&&&&&&&&&&&"+rootText.element("name").getText());
			System.out.println("222&&&&&&&&&&&&"+rootText.element("college").getText());
			System.out.println("333&&&&&&&&&&&&"+rootText.element("telephone").getText());
			System.out.println("444&&&&&&&&&&&&"+rootText.element("notes").getText());
		}
	}
}

用到的jar有:dom4j-1.6.1.jar,freemarker-2.3.13.jar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生活中的思索

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值