使用 XMLParser 在 Android 中解析 XML feed

Parsing XML feed in Android using XMLParser

所以我浏览了无数教程并尝试了很多不同的想法,但我终究无法弄清楚如何解析下面的 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>

这是我的代码 Activity:

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 Activity

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

}

如有任何帮助,我们将不胜感激。

我建议您查看用于(反)序列化 XML 的 simple 库。

只需要创建一个 class 并反序列化 xml。例如:

@Root(name="REQUEST_GUESS_LETTER")
public class Example {

   @Element(name="top_guessed_letters")
   private String guessed;

   @Element(name="top_not_guessed_letters")
   private String not_guessed;

   public Example() {
      super();
   }  

   public Example(String guessed, String not_guessed) {
      this.guessed = guessed;
      this. not_guessed = not_guessed;
   }

   public String getGuessed() {
      return guessed;
   }

   public String getNotGuessed() {
      return not_guessed;
   }
}

然后执行这段代码。

Serializer serializer = new Persister();
File source = new File("example.xml");

Example example = serializer.read(Example.class, source);