【发布时间】:2014-10-06 11:40:26
【问题描述】:
我正在学习如何很好地使用 android 的 DOm 解析器我使用示例 androidHive.com 的 Servivce
“http://api.androidhive.info/pizza/?format=xml”
我正在使用 URLCONnection 连接到具有用户名和密码的服务器,但它返回 nullPointerException。
受保护的静态 InputStream getInputStream(URL url) { 试试{
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);
}
}
}
【问题讨论】:
标签: android xml-parsing inputstream android-parser