Wednesday, 30 January 2013

XML Parsing (Android parse XML file from Assets folder)

1.Sample Order XML file - order.xml

<?xml version="1.0" encoding="utf-8" ?>
<PurchaseOrder>
  <OrderId>5</OrderId>
  <CustomerId>0275125</CustomerId>
  <Email>prashantkoli71@gmail.com</Email>
  <OrderItemDetail>
    <LineNumber>1</LineNumber>
    <ProductSku>12010109Y</ProductSku>
    <Quantity>2.00</Quantity>
    <Price>7.99</Price>
   </OrderItemDetail>
  <OrderItemDetail>
    <LineNumber>2</LineNumber>
    <ProductSku>12010109B</ProductSku>
    <Quantity>900</Quantity>
    <Price>83.50</Price>
   </OrderItemDetail>
  <OrderItemDetail>
    <LineNumber>3</LineNumber>
    <ProductSku>11271581Y</ProductSku>
    <Quantity>16.00</Quantity>
    <Price>8.99</Price>
   </OrderItemDetail>
</PurchaseOrder>

2.Android Application main Layout - main.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout 
 xmlns:tools="http://schemas.android.com/tools"   
  android:layout_width="match_parent"
 android:layout_height="match_parent">
 <TextView  
  android:id="@+id/textView1"  
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" 
   android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true"  
  android:layout_marginTop="14dp"
  android:text="@string/parsed_data"    
  android:textAppearance="?android:attr/textAppearanceMedium"
  android:textStyle="bold" />
 <ScrollView  
  android:id="@+id/scrollView1"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" 
   android:layout_below="@+id/textView1"
  android:layout_marginTop="10dp">
  <LinearLayout
      android:id="@+id/linearLayout1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical" />
 </ScrollView>
</RelativeLayout>

 3.Shopping Cart Java Object - ProductInfo.java

package com.prashant.xml;
public class ProductInfo {
  
 String seqNo = null;
 String itemNumber = "";
 String quantity = "";
 String price = "";
  
 public String getSeqNo() {
  return seqNo;
 }
 public void setSeqNo(String seqNo) {
  this.seqNo = seqNo;
 }
 public String getItemNumber() {
  return itemNumber;
 }
 public void setItemNumber(String itemNumber) {
  this.itemNumber = itemNumber;
 }
 public String getQuantity() {
  return quantity;
 }
 public void setQuantity(String quantity) {
  this.quantity = quantity;
 }
 public String getPrice() {
  return price;
 }
 public void setPrice(String price) {
  this.price = price;
 }
}

4.Custom XML handler for parsing - OrderXMLHandler.java

package com.prashant.xml;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class OrderXMLHandler extends DefaultHandler {
 boolean currentElement = false;
 String currentValue = "";
 String cartId;
 String customerId;
 String email;
 ProductInfo productInfo;
 ArrayList<ProductInfo> cartList;
  
 public String getCartId() {
  return cartId;
 }
 public String getCustomerId() {
  return customerId;
 }
  
 public String getEmail() {
  return email;
 }
 public ArrayList<ProductInfo> getCartList() {
  return cartList;
 }
  
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {
  currentElement = true;
  if (qName.equals("PurchaseOrder")){
   cartList = new ArrayList<ProductInfo>();
  }
  else if (qName.equals("OrderItemDetail")) {
   productInfo = new ProductInfo();
  }
 }
 public void endElement(String uri, String localName, String qName)
 throws SAXException {
  currentElement = false;
  if (qName.equalsIgnoreCase("OrderId"))
   cartId = currentValue.trim();
  else if (qName.equalsIgnoreCase("CustomerId"))
   customerId = currentValue.trim();
  else if (qName.equalsIgnoreCase("Email"))
   email = currentValue.trim();
  else if (qName.equalsIgnoreCase("LineNumber"))
   productInfo.setSeqNo(currentValue.trim());
  else if (qName.equalsIgnoreCase("ProductSku"))
   productInfo.setItemNumber(currentValue.trim());
  else if (qName.equalsIgnoreCase("Quantity"))
   productInfo.setQuantity(currentValue.trim());
  else if (qName.equalsIgnoreCase("Price"))
   productInfo.setPrice(currentValue.trim());
  else if (qName.equalsIgnoreCase("OrderItemDetail"))
   cartList.add(productInfo);
  currentValue = "";
 }
 public void characters(char[] ch, int start, int length)
 throws SAXException {
  if (currentElement) {
   currentValue = currentValue + new String(ch, start, length);
  }
 }
}

5.Android Application main Activity - MainActivity.java

package com.prashant.xml;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.Menu;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        parseXML();
    }
    private void parseXML() {
        AssetManager assetManager = getBaseContext().getAssets();
        try {
            InputStream is = assetManager.open("order.xml");
            SAXParserFactory spf = SAXParserFactory.newInstance();
   SAXParser sp = spf.newSAXParser();
   XMLReader xr = sp.getXMLReader();
   OrderXMLHandler myXMLHandler = new OrderXMLHandler();
   xr.setContentHandler(myXMLHandler);
   InputSource inStream = new InputSource(is);
   xr.parse(inStream);
    
   String cartId = myXMLHandler.getCartId();
   String customerId = myXMLHandler.getCustomerId();
   String email = myXMLHandler.getEmail();
    
   Log.v("abc", cartId);
   LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1);
   TextView tv = new TextView(this);
         tv.setText("Cart Id: " + cartId);
         ll.addView(tv);
         tv = new TextView(this);
         tv.setText("Customer Id: " + customerId);
         ll.addView(tv);
         tv = new TextView(this);
         tv.setText("Email : " + email);
         ll.addView(tv);
         tv = new TextView(this);
         tv.setText("Shopping Cart Info --->");
         ll.addView(tv);
          
   ArrayList<ProductInfo> cartList = myXMLHandler.getCartList();
   for(ProductInfo productInfo: cartList){
    tv = new TextView(this);
          tv.setText("Line No : " + productInfo.getSeqNo());
          ll.addView(tv);
          tv = new TextView(this);
          tv.setText("Item No : " + productInfo.getItemNumber());
          ll.addView(tv);
          tv = new TextView(this);
          tv.setText("Quantity : " + productInfo.getQuantity());
          ll.addView(tv);
          tv = new TextView(this);
          tv.setText("Price : " + productInfo.getPrice());
          ll.addView(tv);
          tv = new TextView(this);
          tv.setText("---");
          ll.addView(tv);
   }
            is.close();
             
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Taking referance from http://www.mysamplecode.com

  output:


Download here:https://www.dropbox.com/s/7824o8osxg8f0cm/XML_Parse_byfolder.zip