Java 读取XML字符

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;
 }

你可能感兴趣的:(java,xml,exception,String,null,encoding)