jdom xpath定位带xmlns命名空间的节点

jdom xpath定位带xmlns命名空间的节点

关键词:jdom xpath xmlns 命名空间 openjweb

 

在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="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context
 xmlns:tx="http://www.springframework.org/schema/tx
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.0.xsd 
 http://www.springframework.org/schema/tx 
 http://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","http://www.springframework.org/schema/beans");
anode = (Element)xpath.selectSingleNode(doc );

上面定义了一个ns命名空间,另外在xpath的查找字符串中,每级节点都要增加 ns:,采用这种方式就可以查找list节点了。

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值