jamesc
jamesc

Reputation: 12837

Android Extract the value of an element from an xml string

How do I get the values of id, created_at and updated at from an XML response after creating a new record on a web server.

The web server responds with an xml response as follows

<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>

The code I use to create the record on the android app (inside an intent service) looks like this

    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());
...

So I assume (correctly?) that responseXml string contains the xml response above All I need to do now is as efficiently as possible extract the id, created_at and updated_at values from that string into a new string for each value.

Any help appreciated

Upvotes: 0

Views: 1177

Answers (1)

nostra13
nostra13

Reputation: 12407

Using DOM it seems to be like:

        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();
        }

Ugly variant, but it must be work.

Upvotes: 2

Related Questions