JDOM是一個開源項目,它基於樹型結構,利用純JAVA的技術對XML文檔實現解析、生成、序列化以及多種操作。JDOM直接為JAVA編程服務。它利用更為強有力的JAVA語言的諸多特性(方法重載、集合概念以及映射),把SAX和DOM的功能有效地結合起來。
JDOM的官方地址:http://www.jdom.org/
1.首先新建一個接口和2個類,為後續做准備
[Moveable.java]
代碼如下:
package com.njupt.zhb.test;
public interface Moveable {
void run();
}
[Plane.java]
代碼如下:
package com.njupt.zhb.test;
public class Plane implements Moveable {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("飛機在翱翔.....");
}
}
[Train.java]
代碼如下:
package com.njupt.zhb.test;
public class Train implements Moveable{
@Override
public void run() {
System.out.println("火車在飛奔....");
}
}
2.新建一個接口,主程序可以調用getBean方法,獲得相應的對象。
代碼如下:
package com.njupt.zhb.test;
public interface BeanFactory {
Object getBean(String id);
}
3.需要解析的xml文件如下:
代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean
id="train"
class="com.njupt.zhb.test.Train">
</bean>
<bean
id="plane"
class="com.njupt.zhb.test.Plane">
</bean>
</beans>
4.解析文件的主類,實現了BeanFactory接口。
代碼如下:
package com.njupt.zhb.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class ClassPathXmlApplicationContext implements BeanFactory {
private Map<String, Object> mapContainer = new HashMap<String, Object>();//用於存放解析出來的id和對象
public ClassPathXmlApplicationContext(String fileName) throws Exception {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(this.getClass().getClassLoader()
.getResourceAsStream(fileName));
Element root = doc.getRootElement();
List list = XPath.selectNodes(root, "/beans/bean");//獲得此節點下的所有值
System.out.println(list.size());
for (int i = 0; i < list.size(); i++) {
Element bean = (Element) list.get(i);
String id = bean.getAttributeValue("id");//獲得id對應的值
String clazz = bean.getAttributeValue("class");//獲得class對應的值
Object o = Class.forName(clazz).newInstance();//Java反射機制,根據類名生成對象
mapContainer.put(id, o);//保存到map中
System.out.println(id + " " + clazz);
}
}
@Override
public Object getBean(String id) {
return mapContainer.get(id);
}
}
5.主程序TestMain調用。
代碼如下:
package com.njupt.zhb.test;
public class TestMain {
public static void main(String[] args) throws Exception {
BeanFactory f = new ClassPathXmlApplicationContext(
"com/njupt/zhb/test/sample.xml");
Object obj1 = f.getBean("train");//獲得標簽為train的對象
Moveable m1 = (Moveable)obj1;//接口調用子類
m1.run();
// //----------------------
Object obj2 = f.getBean("plane");
Moveable m2 = (Moveable) obj2;
m2.run();
}
}
實驗結果:
代碼如下:
2
train com.njupt.zhb.test.Train
plane com.njupt.zhb.test.Plane
火車在飛奔....
飛機在翱翔.....
點擊下載源代碼