Parse Xml On Android
I am trying to use the API for our billing system in an Android Application, but I am having trouble figuring out how to parse the XML that it returns. Here is what my function loo
Solution 1:
Yes SAX parser is the solution and here is the basic code to get you started:
voidparseExampleFunction(){
SAXParserFactoryspf= SAXParserFactory.newInstance();
SAXParsersp= spf.newSAXParser();
XMLReaderxr= sp.getXMLReader();
FilemyFile=newFile( //the XML file which you need to parse );
myFile.createNewFile();
FileInputStreamfOut=newFileInputStream(myFile);
BufferedInputStreambos=newBufferedInputStream( fOut );
/** Create handler to handle XML Tags ( extends DefaultHandler ) */MessagesXMLHandlermyXMLHandler=newMessagesXMLHandler(context);
xr.setContentHandler(myXMLHandler);
xr.parse(newInputSource(bos));
}
// the class where the parsing logic needs to defined.This preferably can be in a different .java file publicclassMessagesXMLHandlerextendsDefaultHandler{
//this function is called automatically when a start tag is encountered@OverridepublicvoidstartElement(String uri, String localName, String qName,Attributes attributes)throws SAXException
//variable localName is the name of the tag//this function is called autiomatically when an end tag is encountered@OverridepublicvoidendElement(String uri, String localName, String qName)throws SAXException {
}
//this function gets called to return the value stored betweeen the closing and opening tags@Overridepublicvoidcharacters(char[] ch, int start, int length)throws SAXException {
//now variable value has the value stored between the closing and opening tags
String value=newString(ch,start,length);
}
}
Solution 2:
for parse xml on android best way is to use SAXParser. i explained it bellow with demo....
first of all create your activity class like as bellw.
publicclassActivityForSaxextendsListActivity {
private ProgressDialog pDialog;
private ItemXMLHandler myXMLHandler;
privateStringrssFeed="https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
private TextView textview;
private ListView mListView;
private ArrayList<HashMap<String, String>> menuItems;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_dom);
textview = (TextView)findViewById(R.id.textView1);
doParsing();
mListView = getListView();
}
publicvoiddoParsing(){
if (isNetworkAvailable()) {
textview.setText("Loading...Please wait...");
newAsyncData().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}
}
classAsyncDataextendsAsyncTask<String, Void, Void> {
@OverrideprotectedvoidonPreExecute() {
menuItems = newArrayList<HashMap<String, String>>();
pDialog = newProgressDialog(ActivityForSax.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
@Overrideprotected Void doInBackground(String... params) {
try {
SAXParserFactoryspf= SAXParserFactory.newInstance();
SAXParsersp= spf.newSAXParser();
XMLReaderxr= sp.getXMLReader();
myXMLHandler = newItemXMLHandler();
xr.setContentHandler(myXMLHandler);
URL_url=newURL(params[0]);
xr.parse(newInputSource(_url.openStream()));
} catch (ParserConfigurationException pce) {
Log.e("SAX XML", "sax parse error", pce);
} catch (SAXException se) {
Log.e("SAX XML", "sax error", se);
} catch (IOException e) {
e.printStackTrace();
}
returnnull;
}
@OverrideprotectedvoidonPostExecute(Void result) {
super.onPostExecute(result);
textview.setText("Done!!!");
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ArrayList<Bean> itemsList = myXMLHandler.getItemsList();
for (inti=0; i < itemsList.size(); i++) {
BeanobjBean= itemsList.get(i);
// creating new HashMap
HashMap<String, String> map = newHashMap<String, String>();
// adding each child node to HashMap key => value
map.put("TITLE :: ", objBean.getTitle());
map.put("DESC :: ", objBean.getDesc());
map.put("PUBDATE :: ", objBean.getPubDate());
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListViewListAdapteradapter=newSimpleAdapter(ActivityForSax.this, menuItems,
R.layout.list_item,
newString[] { "TITLE :: ", "DESC :: ", "PUBDATE :: " }, newint[] {
R.id.name, R.id.email, R.id.mobile });
mListView.setAdapter(adapter);
}
}
publicvoidshowToast(String msg) {
Toast.makeText(ActivityForSax.this, msg, Toast.LENGTH_LONG).show();
}
publicbooleanisNetworkAvailable() {
ConnectivityManagerconnectivity= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
returnfalse;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (inti=0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
returntrue;
}
}
}
}
returnfalse;
}
}
now you need to create default handler class for parsing xml data.
publicclassItemXMLHandlerextendsDefaultHandler {
BooleancurrentElement=false;
StringcurrentValue="";
Beanitem=null;
private ArrayList<Bean> itemsList = newArrayList<Bean>();
public ArrayList<Bean> getItemsList() {
return itemsList;
}
// Called when tag starts@OverridepublicvoidstartElement(String uri, String localName, String qName,
Attributes attributes)throws SAXException {
currentElement = true;
currentValue = "";
if (localName.equals("item")) {
item = newBean();
}
}
// Called when tag closing@OverridepublicvoidendElement(String uri, String localName, String qName)throws SAXException {
currentElement = false;
if (localName.equals("id")) {
item.setId(currentValue);
} elseif (localName.equals("title")) {
item.setTitle(currentValue);
} elseif (localName.equals("desc")) {
item.setDesc(currentValue);
} elseif (localName.equals("pubDate")) {
item.setPubDate(currentValue);
} elseif (localName.equals("link")) {
item.setLink(currentValue);
} elseif (localName.equals("item")) {
itemsList.add(item);
}
}
// Called to get tag characters@Overridepublicvoidcharacters(char[] ch, int start, int length)throws SAXException {
if (currentElement) {
currentValue = currentValue + newString(ch, start, length);
}
}
}
and finally your Bean class like as...
publicclassBean {
privateString id;
privateString title;
privateString desc;
privateString pubDate;
privateString link;
publicStringgetId() {
return id;
}
publicvoidsetId(String id) {
this.id = id;
}
publicStringgetTitle() {
return title;
}
publicvoidsetTitle(String title) {
this.title = title;
}
publicStringgetDesc() {
return desc;
}
publicvoidsetDesc(String desc) {
this.desc = desc;
}
publicStringgetPubDate() {
return pubDate;
}
publicvoidsetPubDate(String pubDate) {
this.pubDate = pubDate;
}
publicStringgetLink() {
return link;
}
publicvoidsetLink(String link) {
this.link = link;
}
}
Solution 3:
- Add
java-json.jar
in library folder - Compile files ('
libs/java-json.jar
') //add this line into your build
Here is the code to convert xml
response to json
response:
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(response.toString());
} catch (JSONException e) {
Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
Post a Comment for "Parse Xml On Android"