Parsing XML File stored in raw folder using XPath

Following code demonstrates how to parse XML file stored in res/raw folder using XPath

Save following file in res – raw folder as data.xml

<?xml version="1.0" encoding="UTF-8"?>
        <title>Using XPath to parse XML</title>
        <author>Pete Houston</author>
        <person id="1">
        <person id="2">
        <person id="3">

package com.example.xmlparsing;

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.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MainActivity extends ListActivity {

	ArrayList<String> mPeople = new ArrayList<String>();
    protected void onCreate(Bundle savedInstanceState) {
        try {
        } 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);
    private void parseData() throws Exception {
        // create an InputSource object from /res/raw
        InputSource inputSrc = new InputSource(getResources().openRawResource(;
        // 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) {
            int len = nodes.getLength();
            for(int i = 0; i < len; ++i) {
                // query value
                Node node = nodes.item(i);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s