Home > Tutorials > Android XML Adventure – Parsing XML using XPath

Android XML Adventure – Parsing XML using XPath


Article Series: Android XML Adventure

Author: Pete Houston (aka. `xjaphx`)

TABLE OF CONTENTS

  1. What is the “Thing” called XML?
  2. Parsing XML Data w/ SAXParser
  3. Parsing XML Data w/ DOMParser
  4. Parsing XML Data w/ XMLPullParser
  5. Create & Write XML Data
  6. Compare: XML Parsers
  7. Parsing XML using XPath
  8. Parsing HTML using HtmlCleaner
  9. Parsing HTML using JSoup
  10. Sample Project 1: RSS Parser – using SAXParser
  11. Sample Project 1: RSS Parser – using DOM Parser
  12. Sample Project 1: RSS Parser – using XMLPullParser
  13. Sample Project 2: HTML Parser – using HtmlCleaner
  14. Sample Project 2: HTML Parser – using JSoup
  15. Finalization on the “Thing” called XML!

=========================================

XPath is a syntax to query directly to the specified tag by name or id or using any pre-defined function to detect the nodes. It’s really useful when it’s coming to parse a lot of data in the form of an array.

You might want to study some about XPath first: W3Schools – XPath Tutorials

Specifically, we will apply XPath in Android platform, there’s a library also named XPath, pre-package in Android framework. Reference to Android XPath Library.

The usage of XPath is pretty much simple:

1. Create a `InputSource` object, from a `String`, from a `InputStream`, from `Resources`, from `Assets` ….

2. Create a `XPath` object

3. Define your XPath expression, which is a `String`.

4. Evaluate above expression from `InputSource` created at step 1.

5. Query data retrieved from evaluation.

That’s it. Here go for an example, I’ll have the following XML file, `data.xml`, and put into `/res/raw` folder.

<?xml version="1.0" encoding="UTF-8"?>
<sample>
	<info>
		<title>Using XPath to parse XML</title>
		<author>Pete Houston</author>
	<list>
		<person id="1">
			<name>Pete Houston</name>
			<age>28</age>
		</person>

		<person id="2">
			<name>Nina Jones</name>
			<age>27</age>
		</person>

		<person id="3">
			<name>Yumin Hanazuki</name>
			<age>22</age>
		</person>
	</list>
	</info>
</sample>

Following above 5 steps, including display data to UI.

package pete.android.tutorial.xml.xpath;

import java.util.ArrayList;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class XPathStudyActivity extends ListActivity {
    // data
	ArrayList<String> mPeople = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
        	parseData();
        } catch(Exception ex) {
        	Toast.makeText(this, "Exception: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        }

        // pass adapter w/ data queried through XPath to ListView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople);
        setListAdapter(adapter);
    }

    private void parseData() throws Exception {
    	// create an InputSource object from /res/raw
    	InputSource inputSrc = new InputSource(getResources().openRawResource(R.raw.data));
    	// query XPath instance, this is the parser
    	XPath xpath = XPathFactory.newInstance().newXPath();
    	// specify the xpath expression
    	String expression = "//name";
    	// list of nodes queried
    	NodeList nodes = (NodeList)xpath.evaluate(expression, inputSrc, XPathConstants.NODESET);

    	Toast.makeText(this, "count: " + String.valueOf(nodes.getLength()),Toast.LENGTH_SHORT).show();
    	// if node found
    	if(nodes != null && nodes.getLength() > 0) {
    		mPeople.clear();
    		int len = nodes.getLength();
    		for(int i = 0; i < len; ++i) {
    			// query value
    			Node node = nodes.item(i);
    			mPeople.add(node.getTextContent());
    		}
    	}
    }
}

The above sample, I’ve tried to query all `name` XML tag from `data.xml` file and display on the list. Very simple usage w/ XPath library!

Have fun,
Pete Houston

Categories: Tutorials Tags: , , , , , ,
  1. Abc
    May 30, 2013 at 5:12 pm

    I ran it using URL resource and it catches Exception: null

  2. sami
    October 10, 2012 at 9:39 pm

    how about if I want to use URL as a xml resource

  3. sam
    May 3, 2012 at 2:35 pm

    Thnxx bro.. u helped me…

  4. Steve c
    February 2, 2012 at 5:40 am

    FINALLY! An example that works!!

  1. No trackbacks yet.

Leave a comment