在编程中,我们常用xml定义数据库配置信息,经过后台处理,获取数据库连接相应信息。
例如,在WEB-INF下定义的数据库配置信息WEB-INF/config/pool-con.xml文件,配置信息如下:
<xml? version="1.0" encoding="UTF-8"?> <Systemconfig> <oracle name="driver" value="oracle.jdbc.driver.OracleDriver" info="oracle数据库驱动"/> <oracle name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" info="oracle数据url"/> <oracle name="username" value="zhangsan" info="数据库用户名"/> <oracle name="password" value="123456" info="用户名密码"/> </Systemconfig>
在这里只做简单的配置,其他自定。
在java进行解析xml信息:
1.获取xml文件路径。类名Test.java信息如下:
public static getpath(){
String path=Test.class.getClassLoader().getResource().getPath();
if(System.getProperty("os.name").toUpperCase().indexOf("WINDOWS")!=-1 && path.startwith("/")){
path=path.subString(1);
}
path=path.split("WEB-INF")[0];
return path;
}
2.解析xml文件,信息如下(filename:文件名,tagname:目标,searchname:查找对象,keyword:查找条件,outname:输出对象):
public static getXml(String filename,String tagname,String searchname,String keyword,String outname){
File file=new File(getpath()+filename);
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=null;
Document doc=null;
String sname="";
String oname="";
try{
builder=factory.newDocumentBuilder();
doc=builder.parese(file);
doc.nomalize();
NodeList nlist=doc.getElementsByTagName(tagname);
for(int i=0;i<nlist.getLength();i++){
Node node=nlist.item(i);
sname=((Element)node).getAttribute(searchname);
if(sname.equal(keyword)){
oname=((Element)node).getAttribute(outname);
break;
}
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
return oname;
}
3.调用方法,显示信息:
String url=Test.getXml("WEB-INF/config/pool-con.xml","oracle","name","url","value");
以上信息仅供参考。