所以我经历了无数的教程并尝试了一堆不同的想法,但是对于我的生活来说,我无法弄清楚如何解析下面的 xml 提要。我正在尝试访问 'top_guessed_letters' 和 top_not_guessed_letters 节点中的值。
<REQUEST_GUESS_LETTER>
<top_guessed_letters>E-T-R-C-A</top_guessed_letters>
<top_not_guessed_letters>O-U-B</top_not_guessed_letters>
<top_correct>I-P-D</top_correct>
<smart_guess>
<smart_guess>R-C-A</smart_guess>
<smart_guess>E-T-R</smart_guess>
</smart_guess>
</REQUEST_GUESS_LETTER>
这是我的 myActivity 代码:
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName("REQUEST_GUESS_LETTER");
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put("top_guessed_letters", parser.getValue(e, top_guessed_letters));
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[]{top_guessed_letters}, new int[]{
R.id.topguessed});
listView.setAdapter(adapter);
XMLPullParser 活动
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
Log.d("xmlTree", url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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
Log.d("getXmlFromUrl ", xml);
return xml;
}
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;
}
Log.d("thisstuff", doc.toString());
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
}
任何帮助,将不胜感激。