zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    mORMot使用基础 2 数据库连接
    【Effective C++】继承与面向对象设计
    【Effective C++】实现
    【Effective C++】设计与声明
    【Effective C++】资源管理
    【Effective C++】构造/析构/赋值运算
    【Effective C++】让自己习惯C++
    【网络基础】计算机网络常考知识点整理
    【C++基础学习】成员对象与对象数组
    C++编程规范纲要要点小结
  • 原文地址:https://www.cnblogs.com/rojas/p/4122593.html
Copyright © 2011-2022 走看看