Dom4j 查找节点或属性

Dom4j  查找节点或属性

例如

  1 查找下面xml中的student节点的age属性,

xpathstr="/students/student/@age";

 2 查找下面xml中的student节点的telephone的值,

xpathstr="/students/student/telephone";

 3 查找下面xml中的student节点的telephone的值,并且要满足name中包含“2030”,用到模糊查找

xpathstr="/students/student[contains("name","2030")]/telephone";

完整的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<students>
  <student name="beijings2014" age="25">
    <college>mobile</college>
    <telephone>888</telephone>
  </student>

     <student name="shanghais2019">
    <college>pc</college>
    <telephone>999</telephone>
  </student>

     <student name="xi'ans2030">
    <college>pad</college>
    <telephone>000</telephone>
  </student>
</students>

  

 具体方法:查找节点或属性,传入Document 和 xpathstr,此处Document 类型为 org.dom4j.Document,

               如果用的是org.w3c.dom.Document则需要转换,可以看之前的一篇"

org.w3c.dom.Document 与org.dom4j.Document互转

"

 1 public String getContentString(Document document,String xpathstr){
 2         
 3         List list = document.selectNodes(xpathstr);
 4         String result="";
 5          
 6         Iterator iter = list.iterator();
 7         iter = list.iterator();
 8         if (iter.hasNext()) {
 9             
10             Object o=iter.next();
11             if(o instanceof Attribute){
12                 Attribute attribute = (Attribute) o;         
13                 //hm.put(attribute.getName(),attribute.getValue());
14                 result=attribute.getValue();
15                 if(debugf){
16                     System.out.println(attribute.getName()+":"+attribute.getValue());
17                 }
18                 
19             }
20             if(o instanceof Element){
21                 Element element = (Element) o;
22                  String name = element.getName();
23                  String value = element.getText();
24                  //hm.put(name, value);
25                  result=value;
26                  if(debugf){
27                  System.out.println(name+":"+value);
28                  }
29             }
30         } else {
31             return result;
32         }
33         return result;
34     }
原文地址:https://www.cnblogs.com/rojas/p/4122593.html