My last question was badly phrased - I am attempting to parse the following xml:
I am having issues parsing the elements inside congestion location:
<tns:camera>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Eastbound</tns:direction>
<tns:order>6</tns:order>
</tns:congestionLocations>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Westbound</tns:direction>
<tns:order>2</tns:order>
</tns:congestionLocations>
<tns:id>130</tns:id>
<tns:offline>false</tns:offline>
<tns:underMaintenance>false</tns:underMaintenance>
</tns:camera>
Using XMLPullParser, I can read the id, offline, etc elements. This works fine. I've written my code to parse the XML below:
// Get our factory and PullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
// Open up InputStream and Reader of our file.
FileInputStream fis = ctx.openFileInput("CameraSites.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
// point the parser to our file.
xpp.setInput(reader);
// get initial eventType
int eventType = xpp.getEventType();
// Loop through pull events until we reach END_DOCUMENT
while (eventType != XmlPullParser.END_DOCUMENT) {
// Get the current tag
String tagname = xpp.getName();
// React to different event types appropriately
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// If we are starting a new <site> block we need
//a new CameraClass object to represent it
curCameraClass = new CameraClass();
}
break;
case XmlPullParser.TEXT:
//grab the current text so we can use it in END_TAG event
curText = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// if </site> then we are done with current Site
// add it to the list.
CameraSites.add(curCameraClass);
} else if (tagname.equalsIgnoreCase(KEY_ID)) {
curCameraClass.setID(curText);
} else if (tagname.equalsIgnoreCase(KEY_MAIN)) {
curCameraClass.setMAIN(curText);
}
break;
default:
break;
}
//move on to next iteration
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
// return the populated list.
return CameraSites;
}
My question is, how would I parse the congestion and direction elements found in the congestion locations? I am parsing these into a get/set method with a class (CameraClass).
Thanks in advance!
Here is the code with your xml..
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class FileActivity extends Activity {
// Progress dialog
ProgressDialog pDialog;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
String data = "<tns:camera>"
+" <tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Eastbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Westbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:description>Bond St looking east</tns:description>"
+"<tns:direction>Eastbound</tns:direction>"
+"<tns:group>SH16-North-Western</tns:group>"
+"<tns:lat>-36.869</tns:lat>"
+"<tns:lon>174.746</tns:lon>"
+"<tns:name>SH16 1 Bond St</tns:name>"
+"<tns:viewUrl>http://www.trafficnz.info/camera/view/130</tns:viewUrl>"
+" </tns:camera>";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new XmlParsing(data).execute(new String[]{null});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class XmlParsing extends AsyncTask<String, Void, String> {
// variables passed in:
String data;
// constructor
public XmlParsing(String data) {
this.data = data;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(FileActivity.this, "Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
FileOutputStream out = openFileOutput("hello.txt",Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
BufferedReader input = new BufferedReader(new InputStreamReader(openFileInput("hello.txt")));
StringBuffer inLine = new StringBuffer();
String text;
while ((text = input.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
input.close();
String finalData =inLine.toString();
InputStream is = new ByteArrayInputStream(finalData.getBytes("UTF-8"));
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("tns:camera");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tns:group");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.v("tns:group : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("tns:viewUrl");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
Log.v("tns:viewUrl : "+ ((Node) nameList1.item(0)).getNodeValue());
if(node.getNodeType() == Node.ELEMENT_NODE)
{
Element e = (Element) node;
NodeList resultNodeList = e.getElementsByTagName("tns:congestionLocations");
int resultNodeListSize = resultNodeList.getLength();
for(int j = 0 ; j < resultNodeListSize ; j++ )
{
Node resultNode = resultNodeList.item(j);
if(resultNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt2 = (Element) resultNode;
NodeList nameList2 = fstElmnt2.getElementsByTagName("tns:congestion");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
Log.v("tns:congestion", ""+((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) resultNode;
NodeList nameList3 = fstElmnt3.getElementsByTagName("tns:direction");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
Log.v("tns:direction--", ""+((Node) nameList3.item(0)).getNodeValue());
}
}
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();
}
}
}
From log you can see the result...
Related
I'm following this tutorial at Techiedreams.com. I want to change the URL of the RSS to my own at http://feeds.feedburner.com/TwitterRssFeedXML. Here are my codes:
SplashActivity.Java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SplashActivty extends Activity {
String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
//wanted http://feeds.feedburner.com/TwitterRssFeedXML instead
RSSFeed feed;
String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity! Reading last update...",
Toast.LENGTH_LONG);
toast.show();
feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivty.this, List_Activity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(RSSFEEDURL);
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
}
RSSItem.Java:
package com.example.samsung.feedrss;
import java.io.Serializable;
public class RSSItem implements Serializable {
private static final long serialVersionUID = 1L;
private String _title = null;
private String _description = null;
private String _date = null;
private String _image = null;
void setTitle(String title) {
_title = title;
}
void setDescription(String description) {
_description = description;
}
void setDate(String pubdate) {
_date = pubdate;
}
void setImage(String image) {
_image = image;
}
public String getTitle() {
return _title;
}
public String getDescription() {
return _description;
}
public String getDate() {
return _date;
}
public String getImage() {
return _image;
}
}
DOMparser:
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
// _feed.clearList();
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}
else if ("pubDate".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
e.printStackTrace();
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
The problem is that my personal URL doesn't work but the original does. Could anyone please solve this issue?
Okay, after some time of work, I've found a solution to this. Just tweak some settings in feedburner.com, make sure to activate SmartFeed under Optimize and you're good to go. Make sure to check any other settings too if SmartFeed alone doesn't work.
UPDATE. I'm really struggling with the answers given (they're not bad answers, I'm just struggling)
It would really help for more detailed answers
I'm pulling in an RSS feed into my app, the pubDate is currently showing up as for example Mon, 10 Nov 2014 03:34:38 +0000.
I need it to show up in a more user friendly manner. I've looked at all the options, SimpleDateFormat..etc, I'm sort of new to Java so all previous suggestions are just going over my head, I'm looking for what I actually need to put in my code.
Code is as follows
AndroidXMLParsingActivity.java
package com.example.myapp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://example.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "description";
static final String KEY_ID = "title";
static final String KEY_LDESC = "content:encoded";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue2(e, KEY_DESC));
map.put(KEY_LDESC, parser.getValue2(e, KEY_LDESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_ID, KEY_LDESC, KEY_DATE}, new int[] {
R.id.name, R.id.content_encoded, R.id.pubDate });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String description = ((TextView) view.findViewById(R.id.description)).getText().toString();
String Ldescription = ((TextView) view.findViewById(R.id.content_encoded)).getText().toString();
String pubDate = ((TextView) view.findViewById(R.id.pubDate)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_ID, name);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_LDESC, Ldescription);
in.putExtra(KEY_DATE, pubDate);
startActivity(in);
}
});
}
}
XMLParser.java
package com.example.myapp;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
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);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
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) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
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 final String getElementValue2( 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 ){
if(child.getNodeType() == Node.CDATA_SECTION_NODE){
return child.getNodeValue();
}
}
}
}
return "";
//return elem.getTextContent();
}
public static String getCharacterDataFromElement(Node elem) {
Node child = elem.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
public String getValue3(Element item, String str){
NodeList n = item.getElementsByTagNameNS("http://purl.org/rss/1.0/modules/content/", str);
String ses = this.getElementValue2(n.item(0));
//return this.getElementValue2(n.item(0));
//return ses;
String mim =ses.replaceAll("(?s)\\<.*?\\>", " \n");
//return Promjena(ses);
return mim;
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public String getValue2(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLParser.getCharacterDataFromElement(n.item(0));
}
}
I'm not sure if you need any more information.
I'm also sure there is a lot of bad or redundant code, any help with that would be great!
Thank you very much!
String date = "Mon, 10 Nov 2014 03:34:38 +0000";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
Date _date = null;
try {
_date = sourceFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(_date .toString());
// print the Date in year month and date
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(targetFormat.format(_date));
You can you SimpleDateFormat class to convert friendly date as following
public String getFriendlyDayString(Date pubDate){
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(pubDate);
}
You can pass your pubDate to like this getFriendlyDateString(pubDate);
i tried replacing
String pubDate = ((TextView) view.findViewById(R.id.pubDate)).getText().toString();
with
String pubDate = "Mon, 10 Nov 2014 03:34:38 +0000";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
Date _date = null;
try {
_date = dateFormat.parse(pubDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(_date .toString());
// print the Date in year month and date
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
((TextView) view.findViewById(R.id.pubDate)).getText().toString();
didn't work...am I on the right track?
I try to get currency from this url http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml. But my parsing doesn't work. This is my code.
http://www.ecb.europa.eu/stats/exchange/eurofxref/html/index.en.html
AndroidXMLParsingActivit.java
package com.androidhive.xmlparsing;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://api.androidhive.info/pizza/?format=xml";
static final String URL = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
// XML node keys
//static final String KEY_ITEM = "item"; // parent node
static final String KEY_ITEM = "Cube"; // parent node
static final String KEY_ID = "currency";
static final String KEY_NAME = "rate";
/*static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
//map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
//map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
//new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
new String[] { KEY_NAME, KEY_ID, KEY_ID }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_ID, cost);
in.putExtra(KEY_NAME, name);
//in.putExtra(KEY_COST, cost);
//in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
SingleMenuItemActivity.java
package com.androidhive.xmlparsing;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_ID = "currency";
static final String KEY_NAME = "rate";
/*static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_NAME);
String cost = in.getStringExtra(KEY_ID);
/*String cost = in.getStringExtra(KEY_COST);
String description = in.getStringExtra(KEY_DESC);*/
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(cost);
Log.i("name", name+"");
Log.i("cost", cost+"");
}
}
XMLParser.java
package com.androidhive.xmlparsing;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
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);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
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) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
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 "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
Original post from here.
File fXmlFile = new File("your XML file");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Cube");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String currency = eElement.getAttribute("currency");
String rate = eElement.getAttribute("rate");
if(currency.isEmpty()){
continue;
}
System.out.println("Ccurrency :" + currency);
System.out.println("Rate : " + rate);
}
}
It's printing the currency and the Rate.
Just replace
File fXmlFile = new File("your XML file");
on
URL url = null;
try {
url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
URLConnection conn = null;
try {
conn = url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And code must run in AsyncTask. I will send full source code through few days.
i have an xml file located at
http://androtrends.hostingsiteforfree.com/direct.xml
i am trying to parse this xml file to use it in my program but every time the program force closes although it has no errors.i am new to java, please help!
Following is the code which i have used in XMLParser.java
public class 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);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
//Parsing XML content and getting DOM element
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) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
//Getting each xml child element value by passing element node name
public String getValue(Element item, String str) {
NodeList n = ((Document) item).getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
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 "";
}
}
The code for Channel.java is
public class Channel extends ListActivity{
String selectedmode, channelName, channelLink;
Intent urlIntent;
// All static variables
static final String DirectURL = "http://androtrends.hostingsiteforfree.com/direct.xml";
static final String FlashURL="http://androtrends.hostingsiteforfree.com/direct.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_Channel = "channel";
static final String KEY_Link = "link";
String xml;
Toast toast;
ArrayList<HashMap<String, String>> menuItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.channels);
selectedmode=getIntent().getExtras().getString("key");
urlIntent=new Intent(Intent.ACTION_VIEW);
Toast.makeText(this, "Wait 60 secs to load the stream...", Toast.LENGTH_LONG).show();
updatechannels();
ListView lv=getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
channelName= ((TextView) view.findViewById(R.id.channelName)).getText().toString();
channelLink= ((TextView) view.findViewById(R.id.channelLink)).getText().toString();
urlIntent.setData(Uri.parse(channelLink));
toast.show();
startActivity(urlIntent);
}
});
}
private void updatechannels() {
// TODO Auto-generated method stub
menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
if (selectedmode.equalsIgnoreCase("direct"))
{
xml = parser.getXmlFromUrl(DirectURL); // getting XML
}else
{
xml = parser.getXmlFromUrl(FlashURL);
}
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// 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_Channel, parser.getValue(e, KEY_Channel));
map.put(KEY_Link, parser.getValue(e, KEY_Link));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_Channel, KEY_Link }, new int[] {
R.id.channelName, R.id.channelLink });
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Try this..
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class NetActivity extends Activity {
String url = "http://androtrends.hostingsiteforfree.com/direct.xml";
// Progress dialog
ProgressDialog pDialog;
ArrayList<String> title;
ArrayList<String> description;
ItemAdapter adapter1;
ListView list;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_net);
list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(url).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new XmlParsing(url).execute(new String[]{null});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class XmlParsing extends AsyncTask<String, Void, String> {
// variables passed in:
String urls;
// constructor
public XmlParsing(String urls) {
this.urls = urls;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(NetActivity.this, "Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL(urls);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("channel");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(""+ ((Node) nameList.item(0)).getNodeValue());
System.out.println("channel : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("link");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
description.add(""+ ((Node) nameList1.item(0)).getNodeValue());
System.out.println("link : "+ ((Node) nameList1.item(0)).getNodeValue());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();
String value = result;
// Log.v("URL Res- - - -", ""+value);
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
}
public ItemAdapter(XmlParsing xmlParsing) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+description.get(position));
return view;
}
}
}
I'm trying to parse the sunrise and sunset time from this webservice and display them into two separate textviews.
I've been trying to follow this tutorial but I'm struggling to understand how to adapt it:
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
In that example the xml file has parent and child nodes and loops to collect them all, in my example I just want to grab two specific parameters and be able to display them.
This is the code I currently have, at the moment it calls the webservice and display the full xml file in an EditText. I need to work out how parse the individual values rather than all of it.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String finalURL = "http://www.earthtools.org/sun/52.77431872/-1.20639/4/12/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
I've been attempting to sort this for a while now and I'm about ready to give up, if anybody could help me out and show me some working code to grab the sunset and sunrise times that would be amazing.
Thanks for looking x
While it's not the "easiest" or "quickest" implementation for parsing XML code, I've always preferred to use the SAXParser utilities from Android.
A great tutorial to follow that breaks everything down step by step is from tutsplus.com
You need to use an XML DOM parser, because it is the easiest.
You should send your results text to the XML parser using DocumentBuilderFactory and then request various values such as sunset and sunrise from the parser.
I suggest following this tutorial: Android XML Parsing Tutorial – Using DOMParser
Sunrise Example (pseudo-code... very pseudo-code):
NodeList nodeList = doc.getElementsByTagName("Morning");
Node node = nodeList.get("sunrise");
String sunrise = node.getValue();
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
You can choose between Sax parser or w3c dom parser.
The above has tutorials on the same.
public class MainActivity extends Activity {
String lsunrise,sunset;
String xml= "<sun >"+
"<version>1.0</version>"+
"<location>"+
"<latitude>52.77431872</latitude>"+
"<longitude>-1.20639</longitude>"+
"</location>"+
"<date>"+
"<day>4</day>"+
"<month>12</month>"+
"<timezone>0</timezone>"+
"<dst>0</dst>"+
"</date>"+
"<morning>"+
"<sunrise>07:45:31</sunrise>"+
"<twilight>"+
"<civil>07:05:54</civil>"+
"<nautical>06:22:57</nautical>"+
"<astronomical>05:41:56</astronomical>"+
"</twilight>"+
"</morning>"+
"<evening>"+
"<sunset>16:02:28</sunset>"+
"<twilight>"+
"<civil>16:42:03</civil>"+
"<nautical>17:24:58</nautical>"+
"<astronomical>18:05:57</astronomical>"+
"</twilight>"+
"</evening>"+
"</sun>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parse();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
void parse()
{ try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
DefaultHandler handler = new DefaultHandler() {
boolean sr=false;
boolean ss=false;
public void startElement(String uri, String localName,String qName,
Attributes atts) throws SAXException {
//System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("sunrise")) {
sr=true;
}
if (qName.equalsIgnoreCase("sunset")) {
ss=true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
//System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException
{
if (sr) {
System.out.println("FSun rise: " + new String(ch, start, length));
sr = false;
}
if (ss) {
System.out.println("Sun set : " + new String(ch, start, length));
ss = false;
}
}
};
saxParser.parse(is, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Outputs snrise and sunset. Modify the above accordingly to get other tag values.
Edit: please see this related question. Parsing sunrise and sunset values from web service
You can parse the xml and set the values to the view.
Check out this tutorial.
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
//here's your xml string.
String test = "<sun xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://www.earthtools.org/sun.xsd\"><version>1.0</version><location><latitude>52.77431872</latitude><longitude>-1.20639</longitude></location><date><day>4</day><month>12</month><timezone>0</timezone><dst>0</dst></date><morning><sunrise>07:45:31</sunrise><twilight><civil>07:05:54</civil><nautical>06:22:57</nautical><astronomical>05:41:56</astronomical></twilight></morning><evening><sunset>16:02:28</sunset><twilight><civil>16:42:03</civil><nautical>17:24:58</nautical><astronomical>18:05:57</astronomical></twilight></evening></sun>";
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(test));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
Log.v("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("morning");
Log.v("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("sunrise : " + eElement.getElementsByTagName("sunrise").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}