Android: How to get values in under specific xml tags
I want to get values under specific tags of my xml file (accessed via url) which look like this:
<SyncLoginResponse>
<Videos>
<Video>
<name>27/flv</name>
<title>scooter</title>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
<thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/106/jpg</thumbnail>
</Video>
<Video>
<name>26/flv</name>
<title>barsNtone</title>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
<thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/104/jpg</thumbnail>
</Video>
</Videos>
<Slideshows>
<Slideshow>
<name>44</name>
&l开发者_C百科t;title>ProcessFlow</title>
<pages>4</pages>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/</url>
</Slideshow>
</Slideshows>
<SyncLoginResponse>
As you can see, there are "name" tags under video while there is also "name" tag under slideshow as well as "title" and "url". I want to get the values under slideshow tag.
So far, I have the following codes:
EngagiaSync.java:
package com.example.engagiasync;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class EngagiaSync extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
public String FileName = "";
public String FileURL = "";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
tv.setText("...PARSE AND DOWNLOAD...");
try {
/* Create a URL we want to load some xml-data from. */
URL url = new URL("http://somedomain.com/tabletcms/tablets/sync_login/jayem30/jayem");
url.openConnection();
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
xr.parse(new InputSource(url.openStream()));
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
//tv.setText(parsedExampleDataSet.toString());
String currentFile;
String currentFileURL;
int x = 1;
Iterator i;
i = parsedExampleDataSet.iterator();
ParsedExampleDataSet dataItem;
while(i.hasNext()){
dataItem = (ParsedExampleDataSet) i.next();
tv.append("\nName:> " + dataItem.getName());
tv.append("\nTitle:> " + dataItem.getTitle());
tv.append("\nPages:> " + dataItem.getPages());
tv.append("\nFile:> " + dataItem.getUrl());
/*
int NumPages = Integer.parseInt(dataItem.getPages());
while( x <= NumPages ){
currentFile = dataItem.getName() + "-" + x + ".jpg";
currentFileURL = dataItem.getUrl() + currentFile;
tv.append("\nName: " + dataItem.getName());
tv.append("\nTitle: " + dataItem.getTitle());
tv.append("\nPages: " + NumPages );
tv.append("\nFile: " + currentFile);
startDownload(currentFile, currentFileURL);
x++;
}
*/
}
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
}
/* Display the TextView. */
this.setContentView(tv);
}
private void startDownload(String currentFile, String currentFileURL ){
new DownloadFileAsync().execute(currentFile, currentFileURL);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading files...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... strings) {
try {
String currentFile = strings[0];
String currentFileURL = strings[1];
File root = Environment.getExternalStorageDirectory();
URL u = new URL(currentFileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(root + "/download/", currentFile));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
ExampleHandler.java:
package com.example.engagiasync;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private StringBuilder mStringBuilder = new StringBuilder();
private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();
// ===========================================================
// Getter & Setter
// ===========================================================
public List<ParsedExampleDataSet> getParsedData() {
return this.mParsedDataSetList;
}
// ===========================================================
// Methods
// ===========================================================
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equals("Slideshow")) {
this.mParsedExampleDataSet = new ParsedExampleDataSet();
}
}
/** Gets be called on closing tags like:
* </tag> */
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("Slideshow")) {
this.mParsedDataSetList.add(mParsedExampleDataSet);
}else if (localName.equals("name")) {
mParsedExampleDataSet.setName(mStringBuilder.toString().trim());
}else if (localName.equals("title")) {
mParsedExampleDataSet.setTitle(mStringBuilder.toString().trim());
}else if(localName.equals("pages")) {
mParsedExampleDataSet.setPages(mStringBuilder.toString().trim());
}else if(localName.equals("url")){
mParsedExampleDataSet.setUrl(mStringBuilder.toString().trim());
}
mStringBuilder.setLength(0);
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
@Override
public void characters(char ch[], int start, int length) {
mStringBuilder.append(ch, start, length);
}
}
ParsedExampleDataSet.java:
package com.example.engagiasync;
public class ParsedExampleDataSet {
private String name = null;
private String title = null;
private String pages = null;
private String url = null;
//name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//title
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
//pages
public String getPages(){
return pages;
}
public void setPages(String pages){
this.pages = pages;
}
//url
public String getUrl(){
return url;
}
public void setUrl(String url){
this.url = url;
}
/*
public String toString(){
return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
}
*/
}
The codes above returns the following result in the UI:
...PARSE AND DOWNLOAD...
Name:> 27/flv
Title:> scooter
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/
In which I expect it to be:
...PARSE AND DOWNLOAD...
Name:> 44
Title:> ProcessFlow
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/
try using DOM parser instead of SAX parser....
input=httpconnection.openHttpConnection(url);
isr = new InputStreamReader(input);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.parse(input, null);
document.getDocumentElement().normalize();
NodeList videosList = document.getElementsByTagName("Video");
for (int i = 0; i < videosList .getLength(); i++)
{
Node node = videosList .item(i);
Element playlistElement = (Element) node;
NodeList title = playlistElement.getElementsByTagName("name");
if (title.item(0).getChildNodes().item(0) != null)
{
Element nameElement = (Element) title.item(0);
title = nameElement.getChildNodes();
Log.v("name===>",((Node) title.item(0)).getNodeValue());
}
//Like wise use the same code for title ,url ,thumbnail...
}
public class XMLHandler extends DefaultHandler
{
boolean result;
boolean customresult;
String temp;
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
{
else if (localName.equalsIgnoreCase("result"))
{
result = true;
}
else if(localName.equalsIgnoreCase("customresult"))
{
customresult =true;
}
}
@Override
public void endElement(String uri, String localName, String qName)throws SAXException {
/** set value */
if (localName.equalsIgnoreCase("name") && result == true)
{
String name = temp; //which is nothing but your name from result tag
}
else if(localName.equalsIgnoreCase("name") && result == true)
{
String name = temp; //which is nothing but your name from customresult tag
}
else if(localName.equalsIgnoreCase("result"))
{
result = false;
}
else if(localName.equalsIgnoreCase("customresult"))
{
customresult = false;
}
}
/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
* -- to get AndroidPeople Character ) */
@Override
public void characters(char[] ch, int start, int length)throws SAXException
{
temp = new String(ch, start, length);
}
}
That is all my friend If you find it useful then dont forget to mark it as an answer.
HI,
Keep boolean variables for the parent tags,
and do check in the EndElement() method that parent tag is true or not;
if it is true then store that particular value to corresponding variable that is all.
e.g.
if you have
<ResultSet>
<result>
<name>a</name>
</result>
<customresult>
<name>avs</customresult>
</ResultSet>
take two variables as result & customresult of boolean type;
mark them as false initially,
check in the startElement() method whether parsing started with Result element if it so
then mark it as a true.
& now you know you are parsing result so you can easily recognize the variable in the
result.
Best Regards,
~Anup
精彩评论