Posted on 2006-03-13 13:59
丁丁 阅读(730)
评论(2) 编辑 收藏 所属分类:
JAVA基础篇
把这个类放到和hibernate.cfg.xml一个目录下,编译执行,注意把需要的包(dom4j)引进去
操作xml基本上就这么东西,你仔细看看,很简单的
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class HiberCFG {
/**
* @param args
*/
public void readXML(){
try{
String fname="hibernate.cfg.xml";
SAXReader reader=new SAXReader();
Document document=reader.read(new File(fname));
Element root=document.getRootElement();
List list=root.selectNodes("/hibernate-configuration/session-factory/property");
for(Iterator it=list.iterator();it.hasNext();){
Node node=(Node)it.next();
if(node.valueOf("@name").equals("hibernate.connection.url")){
//原url
String url=node.getText();
System.out.println(url);
//IP地址前的部分
String a1=url.substring(0,url.indexOf("//")+2);
System.out.println(a1);
//IP地址后部分
String a2=url.substring(url.indexOf(":",(url.indexOf("//")+2)),url.length());
System.out.println(a2);
String newIP="192.168.0.1";
//修改后的url
String newUrl=a1+newIP+a2;
System.out.println(newUrl);
//将新url替换
node.setText(newUrl);
}
}
//将文件保存
String indent=" ";//缩进符号
boolean newLines=true;// 是否产生新行(即一个元素一行)
XMLWriter writer=new XMLWriter(new FileOutputStream(fname),new org.dom4j.io.OutputFormat(indent,newLines,"utf-8"));
writer.write(document);
writer.flush();
writer.close();
System.out.println("成功");
}
catch(Exception ex){
System.out.println("失败");
ex.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
HiberCFG h=new HiberCFG();
h.readXML();
}
}