如何用android中的属性值解析xml数据?

我有一个像下面的xml数据

                                

我正在通过使用下面的XMLParser类来解析它

  public class XMLParser { // constructor public XMLParser() { } /** * Getting XML from URL making HTTP request * @param url string * */ public String getXmlFromUrl(String url) { String xml = null; try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // return XML return xml; } /** * Getting XML DOM element * @param XML string * */ public Document getDomElement(String xml){ Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error: ", e.getMessage()); return null; } catch (SAXException e) { Log.e("Error: ", e.getMessage()); return null; } catch (IOException e) { Log.e("Error: ", e.getMessage()); return null; } return doc; } /** Getting node value * @param elem element */ public final String getElementValue( Node elem ) { Node child; if( elem != null){ Log.e("in element","element"); if (elem.hasChildNodes()){ Log.e("in child","child nodes"); for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){ Log.e("in for","for loop"); child = elem.getFirstChild(); if( child.getNodeType() == Node.TEXT_NODE ){ Log.e("in if condition","if cond"); return elem.getNodeValue(); } } } } return ""; } /** * Getting node value * @param Element node * @param key string * */ public String getValue(Element item, String str) { NodeList n = item.getElementsByTagName(str); return this.getElementValue(n.item(0)); } } 

这是我的活动代码:

 ArrayList<HashMap> menuItems = new ArrayList<HashMap>(); XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML Log.e("string xml","hello"+xml); Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_ITEM); // looping through all item nodes  for (int i = 0; i < nl.getLength(); i++) { // creating new HashMap Log.e("no. of items",""+i); HashMap map = new HashMap(); Element e = (Element) nl.item(i); // adding each child node to HashMap key => value map.put(KEY_NAME, parser.getValue(e, KEY_NAME)); Log.e("names","hi"+parser.getValue(e, KEY_NAME)); menuItems.add(map); } 

我观察到XmLParser中的getElementValue(Node elem)总是返回空String。 我想我需要改变这个方法。我尝试通过改变一些语句但没有找到任何解决方案。

请建议解决方案。