我在学习如何很好地使用 android 的 DOm 解析器我使用示例 androidHive.com 的 Servivce
“ http://api.androidhive.info/pizza/?format=xml ”
我使用 URLCONnection 连接到一个服务器,它有一个用户名和密码来连接,但它返回 nullPointerException。
protected static InputStream getInputStream(URL url) { try{
URLConnection UrlConn = url.openConnection();
UrlConn.setDoInput (true);
UrlConn.setRequestProperty ("trust",
URLEncoder.encode(User,Pass);
UrlConn .connect ();
return UrlConn.getInputStream();
} catch (IOException e) {
return null;
} catch (Exception e) {
return null;
}
这是我的代码:
public static void domparser() throws Exception {
//Get the DOM Builder Factory
pizza=new ArrayList<HashMap<String,String>>();
String urlN="http://api.androidhive.info/pizza/?format=xml";
URL url=new URL(urlN);
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
Document document =
builder.parse(getInputStream(url));
Element root = document.getDocumentElement();
NodeList nodeList = root.getElementsByTagName("menu");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node=nodeList.item(i);
NodeList list=node.getChildNodes();
for(int x=0;list.getLength()>x;x++){
//map=new HashMap<String,String>();
HashMap<String,String> map=new HashMap<String,String>();
Node element=list.item(x);
String name=element.getNodeName();
if (name.equalsIgnoreCase("id")){
map.put("Id",element.getFirstChild().getNodeValue().toString());
} else if (name.equalsIgnoreCase("name")){
map.put("name",element.getFirstChild().getNodeValue().toString());
}
pizza.add(map);
}
}
}