jdom xpath定位帶xmlns命名空間的節點

原文地址:https://www.2cto.com/kf/201306/223851.html

在jdom中用 xpath定位節點通常採用以下方式:

XPath xpath=null;
Element anode = null;
SAXBuilder sb = new SAXBuilder();
Document doc = null;
try
{
    doc = sb.build("xxx.xml");
}
catch(Exception ex)
{
    return "解析xml失敗!";
}

xpath = XPath.newInstance("/節點1/節點2[@屬性1='值1']");
anode=(Element)xpath.selectSingleNode(doc);

但是在處理spring的bean文件時,發現這種方式定位不到想找的節點,下面是openjweb的core-service-demo.xml,現在要查找此文件裏的hibernate配置,文件格式:

<?xml version="1.0" encoding="GB2312"?>

<beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="https://www.springframework.org/schema/context" 
 xmlns:tx="https://www.springframework.org/schema/tx" 
 xsi:schemaLocation="https://www.springframework.org/schema/beans 
 https://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 https://www.springframework.org/schema/context 
 https://www.springframework.org/schema/context/spring-context-3.0.xsd 
 https://www.springframework.org/schema/tx 
 https://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 
 
......

 

<bean id="demosessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource">
   <ref local="demoDatasource" />
  </property>
  <property name="mappingResources">
   <list>
    <value>org/openjweb/core/entity/CommSubSystem.hbm.xml</value>

   ......

  </list></property>

</bean>

</beans>
現在要通過程序查找list節點,但是按照下面的方式發現取不到list的Element:

xpath = XPath.newInstance("/beans/bean/property[@name='mappingResources']/list");

anode = (Element)xpath.selectSingleNode(doc );

後來從網上查找解決方案,發現是因爲beans根節點帶有xmlns命名空間。需要註冊命名空間,見下面的代碼:

xpath = XPath.newInstance("/ns:beans/ns:bean/ns:property[@name='mappingResources']/ns:list");
//ns是隨便起的名字
xpath.addNamespace("ns","https://www.springframework.org/schema/beans");
anode = (Element)xpath.selectSingleNode(doc );

上面定義了一個ns命名空間,另外在xpath的查找字符串中,每級節點都要增加 ns:,採用這種方式就可以查找list節點了。

發佈了2 篇原創文章 · 獲贊 13 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章