dom4j取xml指定节点值方法的备份

自己随便用遍历的方法来取第一个在xml文件中出现的某节点的值的方法1,能满足一些需求。不过有时候需要指定节点的全路径,于是又写了个方法来做,不过发现若xml文件中存在命名空间则取不到值,就自己整理了方法2,在此备份:

 

方法1:

public static String getNoteValue(String xml_str,File file,String note_name){
 
 String result="";
 
 try {  
   Document doc = null;
    if(xml_str!=null&&!"".equals(xml_str)){
   doc=getXmlDoc(xml_str);//用SAXReader获取,此处略
    }else if(file!=null){
   doc = getXmlDoc(file);
    }
   
  if(doc==null)
     return result;
    
  Element root = doc.getRootElement();
  Iterator iter=root.elementIterator();
  List ls=new ArrayList();     
  if(iter!=null)
  {
    while(iter.hasNext())
    {
    Element element = (Element)iter.next();
    String e_name=element.getName();
    String e_value=element.getText();     
     
    if(note_name.equals(e_name)){
     result=e_value;
     break;
    }else if(element.elementIterator()!=null)
      ls.add(element);
    }    
     if(result.length()==0)
      result=getFinalString(ls,note_name);
    }
 } catch (Exception e) {
  e.printStackTrace();
  return null;
 }
 return result;
 }

 

 

方法2:

 

 public static String getExactNoteValue(String xml_str,File file,String node_path){
   if((xml_str==null||"".equals(xml_str.trim()))&&file==null)
    return "";
   String result="";
   try {
    Document doc = null;
    if(xml_str!=null&&!"".equals(xml_str)){
   doc=getXmlDoc(xml_str);
    }else if(file!=null){
   doc = getXmlDoc(file);
    }
     
    Element root=doc.getRootElement();
    String nps=root.getNamespace().getText();
  
   if(nps!=null&&!"".equals(nps)){
      Map map = new HashMap();
      map.put("xmlns",nps);
      if(node_path.startsWith("/")){  
     node_path=node_path.replaceAll("/","/xmlns:");
      }else{
     node_path="/xmlns:"+node_path.replaceAll("/","/xmlns:");
      }
      XPath xp=doc.createXPath(node_path);
      xp.setNamespaceURIs(map);
      Node nn=xp.selectSingleNode(doc);
      if(nn!=null)

      {
        result=nn.getText();

      }
   }else{
    Node node=doc.selectSingleNode(node_path);
      if(node!=null&&node.hasContent()){
    result=node.getText();
     }
   }
  
   } catch (Exception e) {
    e.printStackTrace();  
   }
   return result;
   }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值