• jdom xpath定位带xmlns命名空间的节点(转)


    jdom xpath定位带xmlns命名空间的节点
    2013-06-29      0 个评论       作者:baozhengw
    收藏    我要投稿

    关键词: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节点了。

  • 相关阅读:
    css 父层 透明 子层不透明Alpha
    ecshop循环foreach,iteration,key,index
    ecshop变量介绍
    ecshop 获取某个商品的 所有订单信息 或者销量
    echosp 销量排行 新增实际价格
    ecshop后台模板设置中将非可编辑区改为可编辑区
    ecshop 影响全局的标量lib_main.php
    个人js
    fixed的left:50%,漂浮
    js返回顶部
  • 原文地址:https://www.cnblogs.com/bmaker/p/5605730.html
Copyright © 2020-2023  润新知