如果你了解spring,我相信你应该知道这是spring的配置文件。接下来,我们将自己使用dom4j读取这个配置文件,并解析出里面相关的内容来。
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.document;
import org.dom4j.documentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
public class Main {
public static void main(String[] args) throws documentException {
SAXReader reader = new SAXReader();
document document = reader.read(Main.class.getClassLoader()
.getResourceAsStream("applicationContext.xml"));
Map nsMap = new HashMap();
nsMap.put("ns", "http://www.springframework.org/schema/beans");
XPath xsub = document.createXPath("//ns:beans/ns:bean");
xsub.setNamespaceURIs(nsMap);
List beans = xsub.selectNodes(document);
for (Element bean : beans) {
String id = bean.attributevalue("id");
String clazz = bean.attributevalue("class");
String scope = bean.attributevalue("scope");
System.out.println("id:" + id + ",class:" + clazz + ",scope:" + scope);
List properties = bean.elements();
for (Element proerty : properties) {
String name = proerty.attributevalue("name");
String ref = proerty.attributevalue("ref");
System.out.println("name:" + name + ",ref:" + ref);
}
System.out.println("======================================");
}
}
}
程序运行效果如下图所示,我们可以看到,使用dom4j已经顺利地解析出了xml配置文件里面的内容。



