Android从xml字符串中提取元素的值

时间:2011-10-14 19:35:11

标签: android

如何在Web服务器上创建新记录后从XML响应中获取id,created_at和更新的值。

Web服务器以xml响应响应,如下所示

<mobile-user>
    <active type="boolean">true</active>
    <created-at type="datetime">2011-10-14T14:20:51Z</created-at>
    <id type="integer">4</id>
    <quiz-id type="integer">0</quiz-id>
    <updated-at type="datetime">2011-10-14T14:20:51Z</updated-at>
</mobile-user>

我用来在Android应用程序(在意图服务中)创建记录的代码如下所示

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(NEW_USER_URL);
    StringBuilder sb = new StringBuilder();

    try {
    sb.append("<mobile_user>");
    sb.append("<auth>");
    sb.append(regId);
    sb.append("</auth>");
    sb.append("<quiz_id>");
    sb.append("1");
    sb.append("</quiz_id>");
    sb.append("</mobile_user>");

    StringEntity entity = new StringEntity(sb.toString(), "UTF-8");
    httppost.setEntity(entity);  
    httppost.addHeader("Accept", "application/xml");
    httppost.addHeader("Content-Type", "application/xml");

    HttpResponse response = httpclient.execute(httppost);       
    String responseXml = EntityUtils.toString(response.getEntity());
...

所以我假设(正确?)responseXml字符串包含上面的xml响应 我现在需要做的就是尽可能高效地将该字符串中的id,created_at和updated_at值提取为每个值的新字符串。

任何帮助表示赞赏

2 个答案:

答案 0 :(得分:2)

使用DOM似乎就像:

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document dom;
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader reader = new StringReader(responseXml);
            InputSource source = new InputSource(reader);
            dom = builder.parse(source);
        } catch (ParserConfigurationException e) {
        } catch (SAXException e) {
        } catch (IOException e) {
        }
        if (dom != null) {
            Element root = dom.getDocumentElement();
            NodeList idItem = root.getElementsByTagName("id");
            NodeList createdAtItem = root.getElementsByTagName("created-at");
            NodeList updatedAtItem = root.getElementsByTagName("updated-at");

            String id = idItem.item(0).getChildNodes().item(0).getNodeValue();
            String createdAt = createdAtItem.item(0).getChildNodes().item(0).getNodeValue();
            String updatedAt = updatedAtItem.item(0).getChildNodes().item(0).getNodeValue();
        }

丑陋的变体,但必须有效。

答案 1 :(得分:0)

您可以使用Android / Java提供的标准XML库

http://www.ibm.com/developerworks/opensource/library/x-android/