Dom4j 解析xpath路径带命名空间的xml文件

xml文件内容如下:



 
   
     
         
           
             
               
               
               
             

           

         

     

   

 

 


    1
    2
    3
 

 

java代码如下:

/**
  * configFileName : 文件的存放路径
  * @param configFileName
  */

 public void config(String configFileName){
     this.configFileName = configFileName;
     SAXReader reader = new SAXReader();
     Document document;
     try {

        //下面三行是最关键,将命名空间添加到xpath中,如果xpath路径不带命名空间,只需要取消如下三行代码,其他代码同样使用。
         Map nameSpaceMap = new HashMap();
         nameSpaceMap.put("xs", "http://www.w3.org/2001/XMLSchema");  
         reader.getDocumentFactory().setXPathNamespaceURIs(nameSpaceMap); 


         document = reader.read(configFileName);
         configDBConfig(document);
     } catch (DocumentException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
     } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }
 }
 
 
 private void configDBConfig(Document document) throws Exception  {
  
      //获得xs:sequence节点下所有子节点信息
      Element element1 = (Element)document.selectSingleNode ("NewData/xs:schema/xs:element/xs:complexType/xs:element/xs:complexType/xs:sequence");
      if(null == element1){return;}
          List elements1 = element1.elements();
          for (Iterator it = elements1.iterator(); it.hasNext();) {
          Element e = (Element) it.next();
          System.out.println("name = "+e.attribute("name").getText() + "   type = "+e.attribute("type").getText());
      }
  
  }

你可能感兴趣的:(Dom4j,XML)