利用JDOM解析xml文件 (二)

2014-11-24 10:16:44 · 作者: · 浏览: 4
Context(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.getAttributeva lue("id");//获得id对应的值
String clazz = bean.getAttributeva lue("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调用。
[java]
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();

}
}

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();

}
}

实验结果:
[html]
train com.njupt.zhb.test.Train
plane com.njupt.zhb.test.Plane
火车在飞奔....
飞机在翱翔.....

2
train com.njupt.zhb.test.Train
plane com.njupt.zhb.test.Plane
火车在飞奔....
飞机在翱翔.....