直接上代码进行分析,这是最简单实用的方法。
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