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节点了。

猜你喜欢

转载自blog.csdn.net/mask_v/article/details/79901187