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     }
  • 相关阅读:
    Mac下tomcat的安装与配置
    jquery中的属性和css
    jquery中的选择器
    数组对象元素的添加,String对象,BOM对象以及文档对象的获取
    js中的函数,Date对象,Math对象和数组对象
    js中的循环语句
    js中的运算符和条件语句
    js中的数据类型及其转换
    js的意义,引用方法及变量
    移动端网页项目总结
  • 原文地址:https://www.cnblogs.com/rojas/p/4122593.html
Copyright © 2011-2022 走看看