SAXReader reader=new SAXReader();
String username=null;
String password=null;
Document document=reader.read(new File(你的文件路径加名称));
Element root=document.getrootElement();
List list=root.selectNodes("//hibernate-configuration/session-factory/property");
   for(Iterator it=list.iterator();it.hasNext();)
   {
     Node node1=(Node)it.next();
     if(node1.valueOf(@name).equals("hibernate.connection.username")){
        username=node1.getText();
     }
     if(node1.valueOf(@name).equals("hibernate.connection.password")){
        password=node1.getText();
     }     
   }

解决方案 »

  1.   

    如果我想将
    <property name="hibernate.connection.url">jdbc:mysql://219.238.157.217:3306/idcsc?useUnicode=true</property>
    变成
    <property name="hibernate.connection.url">jdbc:mysql://192.168.1.5:3306/idcsc?useUnicode=true</property>
    应该怎么做???
    谢谢!!
      

  2.   

    把这个类放到和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(); }}