Java 读取XML字符

news/2024/7/4 4:24:09 标签: xml, java, string, exception, encoding, null

String xml=“<?xml version='1.0' encoding='gbk'?><smartresult><product type='ip'>" +
       "<ip>aaaaa</ip><location>北京市 铁通ADSL</location></product></smartresult>”; 

private static String getLocation(String xml){
  String location = null;
  try {
   DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
   DocumentBuilder db=dbf.newDocumentBuilder();
   Document doc=db.parse(new InputSource(new StringReader(xml)));
   XPath xpath=XPathFactory.newInstance().newXPath();
   NodeList nodeList=(NodeList) xpath.evaluate("/smartresult/product", doc, XPathConstants.NODESET);
   if(nodeList != null && nodeList.getLength() > 0){
    for(int i = 0;i < nodeList.getLength();i++){
     Node itemInfo=nodeList.item(i);
     if(xpath.evaluate("location", itemInfo) != null){
      location = xpath.evaluate("location", itemInfo);
     }
    }
   }
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (XPathExpressionException e) {
   e.printStackTrace();
  } catch (Exception e){
   e.printStackTrace();
  }
  return location;
 }


http://www.niftyadmin.cn/n/615131.html

相关文章

并发编程-多进程

一.进程 新进程的创建都是由一个已经存在的进程执行了一个用于创建进程的系统调用而创建的。 1.在UNIX中&#xff1a;fork会创建一个与父进程一摸一样的副本 2.在Windows&#xff1a;系统调用CreateProcess创建进程 进程的状态 程序遇到IO操作(Input、output)&#xff0c;会阻塞…

如何控制HTML中DIV的加载顺序

转载 http://bbl456.blog.sohu.com/72162079.html 目前网站之间相互调用的情况越来越多&#xff0c;比如 需要调用某个第三方提供的一些接口&#xff08;天气预报&#xff09;&#xff0c;或者是第三方提供的广告...... 但是出于各种原因&#xff08;网络故障、服务器故障、软…

js字符串函数(转)

JS自带函数 concat 将两个或多个字符的文本组合起来&#xff0c;返回一个新的字符串。 var a "hello"; var b ",world"; var c a.concat(b); alert(c); //c "hello,world" indexOf 返回字符串中一个子串第一处出现的索引&#xff08;从左到右…

Spring Boot属性配置文件详解

前言 上一篇介绍了Spring Boot的入门&#xff0c;知道了Spring Boot使用“习惯优于配置”&#xff08;项目中存在大量的配置&#xff0c;此外还内置了一个习惯性的配置&#xff0c;让你无需手动进行配置&#xff09;的理念让你的项目快速运行起来。所以&#xff0c;我们要想把S…

struts2为每个线程提供一个action实例

1.struts2为每个线程提供一个action实例,多线程访问时不会出现问题。当使用spring管理struts2的action实例对象时,scope必须配置为prototype或者session,若配置为singleton则多线程访问时会出现问题,例如actionMessage,fieldError等信息会累加,多用户访问时有的用户访问到的是另…

spring-boot结合maven配置不同环境的profile

1、在spring-boot中新建配置文件 spring-boot不同环境配置文件格式为application-{profile}.yml 说明&#xff1a; 如果application.yml中的配置和application-{profile}.yml相冲突时&#xff0c;application.yml中的配置会被覆盖掉。 2、在application.yml中增加属性 spring: …

Hibernate数据缓存策略

Hibernate数据缓存策略 &#xff08;一&#xff09;hibernate数据缓存策略 缓存是数据库数据在内存中的临时容器&#xff0c;它包含了库表数据在内存中的拷贝&#xff0c;位于数据库与数据访问层之间。对于查询操作相当频繁的系统&#xff08;论坛&#xff0c;新闻发布等&…

python-threading

借用虫师的多线程示例&#xff0c;了解多线程的概念。 #!/usr/bin/python # -*- coding: UTF-8 -*- import threading import time def music(): for i in range(1, 3): print music time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) time.sleep(10) print m…