Thursday, 13 June 2013

How to read a xml file and display in listview in Android

Documentbuilder defines the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a Document from XML.
An instance of this class can be obtained from the newDocumentBuilder() method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.
Note that this class reuses several classes from the SAX API. This does not require that the implementor of the underlying DOM implementation use a SAX parser to parse XML document into a Document. It merely requires that the implementation communicate with the application using these existing APIs.

Here is the employeedetails.xml

<?xml version="1.0" encoding="utf-8" ?>
    <Designation>Software Enginner</Designation>
    <Designation>Junior Programmer</Designation>

In activity

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

 * Created by seguro6 on 6/12/13.
public class ReadXml extends ListActivity {

    ArrayList<String> xmlList = new ArrayList<String>();
    public void onCreate(Bundle savedInstanceState) {
            InputStream is=getResources().openRawResource(R.raw.employeedetails);
            DocumentBuilder builder= DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc=builder.parse(is, null);
            NodeList nodes=doc.getElementsByTagName("Details");
            if(nodes != null && nodes.getLength() > 0) {
                int len = nodes.getLength();
                for(int i = 0; i < len; ++i) {
                    // query value
                    Node node = nodes.item(i);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, xmlList);
        catch(Throwable t){
            Toast.makeText(this, "Exception :" + t.toString(), Toast.LENGTH_LONG).show();

1 comment: