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