meklod400
meklod400

Reputation: 129

Android read xml via http

Is there any working xml read via http tutorial or example?

I have a server which contain the next lines url: http://192.168.0.1/update.xml:

<?xml version='1.0' encoding='UTF-8'?>
<Version>1</Version>

And I would like to shown the "1" number to a TextView. How can I do it?

Upvotes: 0

Views: 1811

Answers (2)

S.Thiongane
S.Thiongane

Reputation: 6905

Here is a piece of code you can adapt to your desires :

To get the remote file content :

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet("my_url");        
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            try {               
                String response = client.execute(get,responseHandler);

            } catch (Exception e) {
                Log.e("RESPONSE", "is "+e.getMessage());                
            }

To parse the XML string :

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(new StringReader(response));
            String value = null;

        while(xpp.getEventType() !=XmlPullParser.END_DOCUMENT){ // loop from the beginning to the end of the XML document

            if(xpp.getEventType()==XmlPullParser.START_TAG){

                if(xpp.getName().equals("version")){
                    // start tag : <version>
                                    // do some stuff here, like preparing an 
                                    // object/variable to recieve the value "1" of the version tag
                }
            }
            else if(xpp.getEventType()==XmlPullParser.END_TAG){             

                       // ... end of the tag: </version> in our example             
                }
                    else if(xpp.getEventType()==XmlPullParser.TEXT){ // in a text node
                 value = xpp.getText(); // here you get the "1" value 
        }

        xpp.next(); // next XPP state
    }                  

Upvotes: 2

MaxAlexander
MaxAlexander

Reputation: 560

This is not a particularly complicated task and it is covered in some detail here on the Android developer site.

Upvotes: 0

Related Questions