利用JDOM解析xml文件
原创
©著作权归作者所有:来自51CTO博客作者ali莫川的原创作品,请联系作者获取转载授权,否则将追究法律责任
利用JDOM解析xml文件
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
火车在飞奔....
飞机在翱翔.....