分享

用dom4j对带有命名空间的xml文件使用xpath取值

 Chi_Way 2011-04-22
关于用dom4j对带有命名空间的xml文件使用xpath取值的例子

xml文件如下:

java代码如下:

Document document = new SAXReader().read( new File( filename ) ); //filename为文件名

//设置http://www./dataspec/映身名为xmlns
Map map = new HashMap();
map.put("xmlns", "http://www./dataspec/");
 
当然map的key值可以指定为任何值,不一定得为"xmlns"
只要把xpath中的值修改为你定义的值即可
 
 
 
 

//下面是取rqQ结点值
XPath xPath = this.getDocument().createXPath(
   "//xmlns:head//xmlns:publicHead//xmlns:sssq//xmlns:rqQ");
 
 
如果上面map中key值不为"xmlns",为"aa"则该语句可写为
XPath xPath = this.getDocument().createXPath(
   "//aa:head//aa:publicHead//aa:sssq//aa:rqQ");

xPath.setNamespaceURIs( map );
String startDate = xPath.selectSingleNode( document ).getText();

//下面是取rqZ结点值
xPath = this.getDocument().createXPath(
   "//xmlns:head//xmlns:publicHead//xmlns:sssq//xmlns:rqZ");
xPath.setNamespaceURIs( map );
String endDate = xPath.selectSingleNode( document ).getText();

 
 
 
 
 
另外不用xpath的时候,可以给SaxReader的DocumentFactory设定命名空间map
此时便可以用document的selectNodes等方法了
如:saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
document.selectSingleNode("//xmlns:head//xmlns:publicHead//xmlns:sssq//xmlns:rqZ");

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多