质检报告哪里办多少钱:用dom4j对带有命名空间的xml文件使用xpath取值

来源:百度文库 编辑:九乡新闻网 时间:2024/04/28 21:33:32
关于用dom4j对带有命名空间的xml文件使用xpath取值的例子

xml文件如下:

java代码如下:

Document document = new SAXReader().read( new File( filename ) ); //filename为文件名
//设置http://www.test.com/dataspec/映身名为xmlns
Map map = new HashMap();
map.put("xmlns", "http://www.test.com/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");