dom4j讀取spring配置文件

/*
  * 使用dom4j讀取spring的配置文件
  * */
  public void readSpringXml(String filename){
   //創建讀取器
   SAXReader saxReader= new SAXReader();
   //xml存放容器
   Document document = null;
   try{
    //得到文件路徑
    URL xmlpath = this.getClass().getClassLoader().getResource(filename);
   // System.out.println(xmlpath);
    document = saxReader.read(xmlpath);
    //創建命名空間容器
    Map<String,String> nsMap = new HashMap<String,String>();
    //插入命名空間
    nsMap.put("ns","http://www.springframework.org/schema/beans");
    //創建beans/bean的查詢路徑
    XPath xsub = document.createXPath("//ns:beans/ns:bean");
    //設置命名空間
    xsub.setNamespaceURIs(nsMap);
    //得到所有bean節點
     List<Element> beans =  xsub.selectNodes(document);
     for(Element element:beans){
      //得到屬性值
     String id = element.attributeValue("id");
        String clazz = element.attributeValue("class");
        System.out.println("id-->"+id+" class-->"+clazz);
        //得到property的數據
          //創建查詢路徑
           XPath propertyxsub = element.createXPath("ns:property");
           //設置命名空間
           propertyxsub.setNamespaceURIs(nsMap);
           //得到bean對象下的property節點
           List<Element> propertys = propertyxsub.selectNodes(element);
           for(Element property: propertys){
            String propertyName = property.attributeValue("name");
            String propertyClazz = property.attributeValue("ref");
            System.out.println("propertyName-->"+propertyName+" properyClazz-->"+propertyClazz);
           }
     }
   
   }catch(Exception e){}
  }

 

 過程中出現了錯誤:java.lang.NoClassDefFoundError: org/jaxen/JaxenException

 原因爲:除去必須有一個dom4j.jar外,還必須有一個jaxen-1.1.1.jar 文件,因爲使用dom4j時調用了XPath,

 而沒有在項目中加載jaxen-xx.xx.jar jaxen是一個用Java開發的XPath 引擎,支持JDOM, dom4j 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章