Today i am going to discuss about parsing XML in android using DOM parser. Also i am demonstrating how to update ListView with parsed XML data.

Download Code

The XML Structure

In this tutorial i’ll will be parsing the following XML file. You can get this xml file by accessing https://api.androidhive.info/pizza/?format=xml

<?xml version="1.0" encoding="UTF-8"?>
<menu>
    <item>
        <id>1</id>    
        <name>Margherita</name>
        <cost>155</cost>
        <description>Single cheese topping</description>
    </item> 
    <item>
        <id>2</id>    
        <name>Double Cheese Margherita</name>
        <cost>225</cost>
        <description>Loaded with Extra Cheese</description>
    </item> 
    <item>
        <id>3</id>    
        <name>Fresh Veggie</name>
        <cost>110</cost>
        <description>Oninon and Crisp capsicum</description>
    </item> 
    <item>
        <id>4</id>    
        <name>Peppy Paneer</name>
        <cost>155</cost>
        <description>Paneer, Crisp capsicum and Red pepper</description>
    </item> 
    <item>
        <id>5</id>    
        <name>Mexican Green Wave</name>
        <cost>445</cost>
        <description>Onion, Crip capsicum, Tomato with mexican herb</description>
    </item> 
</menu>

Writing XML Parser Class

In your project create a class file and name it as XMLParser.java. The parser class mainly deals the following operations.

⇒ Getting XML content by making HTTP request
⇒ Parsing XML content and getting DOM element of xml.
⇒ Get each xml child element value by passing element node name.

Getting XML content by making HTTP Request

This function will get XML by making an HTTP Request.

public String getXmlFromUrl(String url) {
		String xml = null;

		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			xml = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// return XML
		return xml;
	}

Parsing XML content and getting DOM element

After getting XML content we need to get the DOM element of the XML file. Below function will parse the XML content and will give you DOM element.

public Document getDomElement(String xml){
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
		        is.setCharacterStream(new StringReader(xml));
		        doc = db.parse(is); 

			} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
	            return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}
                // return DOM
	        return doc;
	}

Get each xml child element value by passing element node name

public String getValue(Element item, String str) {		
	NodeList n = item.getElementsByTagName(str);		
	return this.getElementValue(n.item(0));
}

public final String getElementValue( Node elem ) {
	     Node child;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                 if( child.getNodeType() == Node.TEXT_NODE  ){
	                     return child.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
  }	

Usage

Following is the code snippet for handling xml operations. I am using xml parser class so far we built and looping through each xml element and getting the child data.

// All static variables
static final String URL = "https://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";

XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element

NodeList nl = doc.getElementsByTagName(KEY_ITEM);

// looping through all item nodes <item>		
for (int i = 0; i < nl.getLength(); i++) {
	String name = parser.getValue(e, KEY_NAME); // name child value
	String cost = parser.getValue(e, KEY_COST); // cost child value
	String description = parser.getValue(e, KEY_DESC); // description child value
}

Parsing XML data and updating into ListView

In my previous tutorial Android ListView Tutorial i explained how to create listview and updating with list data. Below i am implementing same listview but the list data i am updating is from parsed xml. This ListView has multiple sub text like name, cost and description.

public class AndroidXMLParsingActivity extends ListActivity {

	// All static variables
	static final String URL = "https://api.androidhive.info/pizza/?format=xml";
	// XML node keys
	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_ID = "id";
	static final String KEY_NAME = "name";
	static final String KEY_COST = "cost";
	static final String KEY_DESC = "description";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL); // getting XML
		Document doc = parser.getDomElement(xml); // getting DOM element

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		// looping through all item nodes <item>
		for (int i = 0; i < nl.getLength(); i++) {
			// creating new HashMap
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key => value
			map.put(KEY_ID, parser.getValue(e, KEY_ID));
			map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
			map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
			map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

			// adding HashList to ArrayList
			menuItems.add(map);
		}

		// Adding menuItems to ListView
		ListAdapter adapter = new SimpleAdapter(this, menuItems,
				R.layout.list_item,
				new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
						R.id.name, R.id.desciption, R.id.cost });

		setListAdapter(adapter);

		// selecting single ListView item
		ListView lv = getListView();
                // listening to single listitem click
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
				String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
				String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
				
				// Starting new intent
				Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
				in.putExtra(KEY_NAME, name);
				in.putExtra(KEY_COST, cost);
				in.putExtra(KEY_DESC, description);
				startActivity(in);

			}
		});
	}
}
android xml parsing and updating to listview
Subscribe
Notify of
guest
30 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] besteht mehrere Textelemente zuweisen, ich habe bereits eine hilfreiche Webseite gefunden: Android XML Parsing Tutorial | AndroidHive | Tutorials, Games, Apps, Tips Kann mit bitte jemand helfen, wie ich das Beispiel umschreiben muss, um eine lokale Datei aufrufen […]

trackback

[…] data in files. It is easy to parse and access data stored in JSON format. Previously i explained parsing XML and today i am going to discuess parsing JSON data with an […]

trackback

[…] going further make sure that you covered Android XML Parsing Tutorial and Android ListView Tutorial […]

trackback

[…] followed a tutorial located here: http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/ and so far everything worked fine with it. However this only worked nice when there were specific […]

trackback

[…] data in files. It is easy to parse and access data stored in JSON format. Previously i explained parsing XML and today i am going to discuess parsing JSON data with an […]

trackback

[…] found a Tutorial: http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/ But this saves the parsed Data in a ListView. But I want to save it all in a TextView. I want every […]

trackback

[…] found a Tutorial: http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/ But this saves the parsed Data in a ListView. But I want to save it all in a TextView. I want every […]

Ravi Tamada
4 years ago

It will be useful if you post the xml parsing code too.

Udhay Parkesh
Udhay Parkesh
4 years ago
Reply to  Ravi Tamada

And i want to know how to get the parent node and child node inside it

ex:

udhay

this is have to parse in listview as per your tutorial sir…

Ravi Tamada
4 years ago
Reply to  Udhay Parkesh

Have you tried jackson library to parse xml?

Udhay Parkesh
Udhay Parkesh
4 years ago
Reply to  Ravi Tamada

Nope sir

Udhay Parkesh
Udhay Parkesh
4 years ago
Reply to  Ravi Tamada

is there any tutorial for jackson lib i dont know about this lib..

Udhay Parkesh
Udhay Parkesh
4 years ago
Reply to  Ravi Tamada

This is my coding :

// DownloadXML AsyncTask
private class DownloadXML extends AsyncTask {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressbar
pDialog = new ProgressDialog(MainActivity.this);
// Set progressbar title
pDialog.setTitle(“Android Simple XML Parsing using DOM Tutorial”);
// Set progressbar message
pDialog.setMessage(“Loading…”);
pDialog.setIndeterminate(false);
// Show progressbar
pDialog.show();
}

@Override
protected Void doInBackground(String… Url) {
try {
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Download the XML file
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Locate the Tag Name
nodelist = doc.getElementsByTagName(“item”);

} catch (Exception e) {
Log.e(“Error”, e.getMessage());
e.printStackTrace();
}
return null;

}

@Override
protected void onPostExecute(Void args) {

for (int temp = 0; temp < nodelist.getLength(); temp++) {
Node nNode = nodelist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
// Set the texts into TextViews from item nodes
// Get the title
textview.setText(textview.getText() + "Title : "
+ getNode("id", eElement) + "n" + "n");
// Get the description
textview.setText(textview.getText() + "Description : "
+ getNode("locale", eElement) + "n" + "n");
// Get the link
textview.setText(textview.getText() + "Link : "
+ getNode("base_url", eElement) + "n" + "n");
// Get the date
textview.setText(textview.getText() + "Date : "
+ getNode("timezone", eElement) + "n" + "n" + "n"
+ "n");
}
}
// Close progressbar
pDialog.dismiss();
}
}

// getNode function
private static String getNode(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}

Udhay Parkesh
Udhay Parkesh
4 years ago

Sir this is my coding of parser using Asynctask

Nicholas Ocholla
4 years ago

Ravi’s Tutorial are the best Android Tutorials out there. Simple, easy to understand and always works as expected. Thanks Ravi.

Krishna Kumar
Krishna Kumar
4 years ago

please share how to parse quandl api into a list view.. since its json is of complex

Mitesh Makwana
Mitesh Makwana
4 years ago

is it possible to use post method while xml parsing ?

any suggestion please

Ravi Tamada
4 years ago
Reply to  Mitesh Makwana

Have you ever tried using Retrofit?

Mitesh Makwana
Mitesh Makwana
4 years ago
Reply to  Ravi Tamada

no

Mitesh Makwana
Mitesh Makwana
4 years ago
Reply to  Ravi Tamada

thanks your suggestion always help me

Ravi Tamada
4 years ago
Reply to  Mitesh Makwana

You are welcome 🙂

Shylendra Madda
3 years ago

very very very thanks a lot Ravi, It is very helpful for me.

Ravi Tamada
3 years ago

You are welcome. Consider reading JSON articles over XML.

Dhaval jotaniya
Dhaval jotaniya
3 years ago

how to parse this type of xml file

simon
simon
2 years ago

I hope there is a mordern update to this tutorial
1.It causes NetworkOnMainThreadException
2.org.apache.http packages was removed since API level 23

Reena Kor
Reena Kor
2 years ago
Reply to  simon

use AsyncTask

Garuda Di Dada ku
Garuda Di Dada ku
1 year ago

comment image

Udhay Parkesh
Udhay Parkesh
4 years ago

Hi i am udhay i use your codings for retrieving my xml format response but it shows null errors

java.lang.NullPointerException: Attempt to invoke interface method ‘int org.w3c.dom.NodeList.getLength()’ on a null object reference

and my repsponse URL is:
http://arocos.com/index.php/rest//V1/store/storeConfigs
Please help me..
Thank you in advance..

30
0
Would love your thoughts, please comment.x
()
x