Thursday, December 26, 2013

XML Parsing using DOM parser in Android

Parsing is the technique to read the value of one object to convert it to another type.

DOM Parser-The Java DOM API comes with the JDK. The DOM(Document Object Model) Parser loads the complete XML content as Tree structure in the memory.
We can traverse(iterate) through the node and nodelist to get the content of the XML.


SAX Parser(Simple API for XML)-It doesn’t load the complete XML into the memory,it parses the XML line by line triggering different events as and when it encounters different elements like: opening tag, closing tag, character data, comments and so on. This is the reason why SAX Parser is called an event based parser.
It's event based which parse XML file step by step so much suitable for large XML Files. SAX XML Parser fires event when it encountered opening tag, element or attribute and the parsing works accordingly. It’s recommended to use SAX XML parser for parsing large xml files in Java because it doesn't require to load whole XML file in Java and it can read a big XML file in small parts.


Difference between SAX and DOM
SAX:
-Parse node by node
-Doesn't store the XML in memory
-We can insert or delete a node.
-SAX is an event based parser.
-SAX is a simple API for XML
-SAX generally runs a little faster than DOM.
DOM:
-Stores the entire XML document into memory before processing.
-Occupies more memory
-We can insert or delete nodes.
-Traverse in any direction.
-DOM is a tree model parser.
-DOM generally runs a little slower than SAX.

Now I am showing one example by using DOM

home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/appbg"
    android:orientation="vertical" >


        <ListView
            android:id="@id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="300dp"
            android:cacheColorHint="#00000000"
            android:scrollbars="vertical" >
        </ListView>
</LinearLayout>

cat_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/list_selector"
    android:orientation="horizontal" >
 
<TextView
            android:id="@+id/cat"
            android:layout_width="wrap_content"
            android:layout_height="33dp"
            android:layout_marginLeft="10dp"
            android:text="@string/Subcategories"
            android:textColor="@color/Black"
             android:layout_marginTop="5dp"
            android:textSize="15dp"
            android:textStyle="bold" />

</LinearLayout>

Home.java


public class Home extends ListActivity  {

ListView lv;

ListAdapter adapter;

final ArrayList<HashMap<String, String>> catItems = new ArrayList<HashMap<String, String>>();
public static String URLCAT = "http://www.oxyandroid.com/oxyandroid.php?type=1&cat=220";

static final String KEY_CATEGORY = "Category";
static final String KEY_CATID = "categoryId";
static final String KEY_CATEGORYNAME = "categoryName";

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
new RetreiveFeedTask().execute(URLCAT);
}

public void demo() {
adapter = new SimpleAdapter(this, catItems, R.layout.cat_adapter,
new String[] { KEY_CATEGORYNAME }, new int[] { R.id.cat });

setListAdapter(adapter);

/* If we are not using android list activity then we will use the below code
                   adapter = new SimpleAdapter(this, listSubCat, R.layout.cat_adapter,
new String[] { "subcate" }, new int[] { R.id.cat });

  lv1.setAdapter(adapter);*/

}

class RetreiveFeedTask extends AsyncTask<String, Void, Integer> {

private ProgressDialog dialog1;

protected void onPreExecute() {
dialog1 = ProgressDialog.show(Home.this, "", "Loading...");

}

protected void onPostExecute(Integer feed) {
try {
dialog1.dismiss();
demo();
} catch (Exception e) {
e.printStackTrace();
}
super.onPostExecute(feed);

}

@Override
protected Integer doInBackground(String... arg0) {
// TODO Auto-generated method stub

try {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URLCAT);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_CATEGORY);

// 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_CATID, parser.getValue(e, KEY_CATID));
map.put(KEY_CATEGORYNAME,
parser.getValue(e, KEY_CATEGORYNAME));
// adding HashMap to ArrayList

catItems.add(map);
}
} catch (Exception e) {
}
return null;
}

}
}

//////////////////////////////////////////////////////////////////////////
//Using DOM parser
XMLParser.java

public class XMLParser {

// constructor
public XMLParser() {

}

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);
//Log.i("XML Parser", "xml=" + xml);

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

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) {
return null;
} catch (SAXException e) {
return null;
} catch (IOException e) {
return null;
}

return doc;
}

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 "";
}

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

No comments:

Post a Comment