How to read XML file in android

To start with use DOM parser. Since its much lesser code, and easy to follow. SAX parser is just too much code to start with. People will argue that SAX is faster, yes it is, but DOM is easier, lesser code and lesser bugs.

If you must move to SAX, first measure your response times when using DOM, and only if parsing is causing you the most pain, then move to SAX. Or else DOM does a wonderful job.


Try this out first:

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {

Button btn;
TextView tvXml;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn = (Button) findViewById(R.id.button1);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Load XML for parsing.
            AssetManager assetManager = getAssets();
            InputStream inputStream = null;
            try {
                inputStream = assetManager.open("textxml.xml");
            } catch (IOException e) {
                Log.e("tag", e.getMessage());
            }

            String s = readTextFile(inputStream);
            TextView tv = (TextView)findViewById(R.id.textView1);
            tv.setText(s);
        }
    });
}


private String readTextFile(InputStream inputStream) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte buf[] = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {

    }
    return outputStream.toString();
}
}

There is several ways to read a XML in Android. My first option is DocumentBuilder since do not create an API version restriction (is available since API Level 1).

An example from one of my projects:

public Document parseXML(InputSource source) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(false);
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(source);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
 }

How do you read the file and access the document values after this, well, its pretty basic, just Google it.