准备jar包:dom4j-1.6.1.jar
xml结构如下:
<?xml version="1.0" encoding="UTF-8"?>
<plans>
<plan>
<id>1</id>
<site>天王</site>
<desc>见面时间</desc>
<type>must</type>
<starttime>9:00</starttime>
<endtime>11:00</endtime>
</plan>
<plan>
<id>2</id>
<site>盖地虎</site>
<desc>买买买,顺便解决午饭</desc>
<type>must</type>
<starttime>预计12:00 </starttime>
<endtime>~ 13:35</endtime>
</plan>
<plan>
<id>3</id>
<site>宝塔</site>
<desc>无描述</desc>
<type>must</type>
<starttime>预计14:20</starttime>
<endtime>~ 16:00</endtime>
</plan>
<plan>
<id>4</id>
<site>镇河妖</site>
<desc>哪里跑?!!!</desc>
<type>must</type>
<starttime>18:00</starttime>
<endtime>20:00</endtime>
</plan>
<plan>
<id>51</id>
<site>--</site>
<desc>无描述</desc>
<type>choose</type>
<starttime>--:--</starttime>
<endtime>--:--</endtime>
</plan>
<plan>
<id>52</id>
<site>--</site>
<desc>无描述</desc>
<type>choose</type>
<starttime>--:--</starttime>
<endtime>--:--</endtime>
</plan>
</plans>
Java 代码:
package com.xml.main;
import java.io.File;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ReadXmlDemo {
public static void readXml() {
try {
/* 读取Web应用的地址 */
// String path = new File("").getCanonicalPath();
// path = path.substring(0, path.length() - 3);
// File file = new File(path+ "webapps/项目名/WEB-INF/classes/xml文件在项目中的路径/plan.xml"); // 针对 Tomcat
File file = new File("F:/projectMyecplise10/ReadXml/src/com/xml/main/plan.xml"); // 读取 Java 应用的地址
SAXReader reader = new SAXReader();
Document document = reader.read(file);
Element element = document.getRootElement();
Element foo;
for (Iterator<?> item = element.elementIterator("plan"); item.hasNext();) {
foo = (Element) item.next();
foo.elementText("id");
foo.elementText("site");
foo.elementText("desc");
foo.elementText("type");
foo.elementText("starttime");
foo.elementText("endtime");
}
}
catch (Exception e) {
e.printStackTrace();
System.out.println(" >_< /~~ 哎呀抛异常了 .. ");
}
}
}