您的位置:首页 > 其它

Dom4j 查找节点或属性

2014-11-26 10:22 246 查看
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互转

"

public String getContentString(Document document,String xpathstr){

List list = document.selectNodes(xpathstr);
String result="";

Iterator iter = list.iterator();
iter = list.iterator();
if (iter.hasNext()) {

Object o=iter.next();
if(o instanceof Attribute){
Attribute attribute = (Attribute) o;
//hm.put(attribute.getName(),attribute.getValue());
result=attribute.getValue();
if(debugf){
System.out.println(attribute.getName()+":"+attribute.getValue());
}

}
if(o instanceof Element){
Element element = (Element) o;
String name = element.getName();
String value = element.getText();
//hm.put(name, value);
result=value;
if(debugf){
System.out.println(name+":"+value);
}
}
} else {
return result;
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: