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 ="\r\n" + 
				"\r\n" + 
				"崔卫兵浙江大学62354666男,1982年生,硕士,现就读于北京邮电大学\r\n" + 
				"王鹏北京大学62358888男,1987年生,硕士,现就读于中国农业大学\r\n" + 
				"王阿道 沈阳大学66666666男,1982年生,硕士,现就读于北京邮电大学\r\n" + 
				"刘桂上海大学88888888男,1982年生,硕士,现就读于北京邮电大学\r\n" + 
				"";
		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

你可能感兴趣的:(DOM4J,JAVA,XML,iterator,element)