i have a xml file
<?xml version="1.0" encoding="utf-8"?>
<NewDataSet> <Password>abcd</Password> </NewDataSet>
how to get the string "abcd" from the above xml file .
I am very new to android platform, please help me out
thanks in advance
From your comment and question, i will suggest you to refer this links:
http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html
http://www.ibm.com/developerworks/opensource/library/x-android/
http://www.androidpeople.com/android-xml-parsing-tutorial-%E2%80%93-using-domparser
From first link, you can go step-by-step and second link includes examples for all the parsing techniques.
I suggest to go with SAX(Simple API for XML) Parser.
in my opinion it's easier to understand something via an example, and even more, if we know example what we expect from that example to do.
So I'll post a little sample, which does nothing else but what you need: reads the password from that xml file and returns it in it's readPassword() method:
import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class XmlSample
{
private static final String xmlSource =
"<?xml version='1.0' encoding='utf-8'?>" +
"<NewDataSet>" +
" <Password>abcd</Password>" +
"</NewDataSet>";
public final class MyXmlHandler extends DefaultHandler
{
/**
* the Password tag's value
*/
private String password;
/**
* for keeping track where the cursor is right now
*/
private String currentNodeName;
public MyXmlHandler()
{
}
/**
* It is called when starting to process a new element (tag)
* At this point you change the currentNodeName member
*/
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException
{
this.currentNodeName = localName;
}
/**
* It is called when an element's processing has finished
* ("</ _tag>" or "... />" is reached)
* Clear the currentNodeName member
*/
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{
this.currentNodeName = null;
}
/**
* It is called when the currentNodeName tag's body is processed.
* In the ch[] array are the character values of that element.
*/
#Override
public void characters(char ch[], int start, int length)
{
if (this.currentNodeName.equals("Password"))
password = new String(ch, start, length);
}
public String getPassword()
{
return password;
}
}
public String readPassword() throws Exception
{
//create an inputSource from the xml value;
//when you get this xml from the server via http, you should use something like:
//HttpEntity responseEntity = response.getEntity();
//final InputSource input = new InputSource(responseEntity.getContent());
final InputSource input = new InputSource(new StringReader(xmlSource));
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
MyXmlHandler myHandler = new MyXmlHandler();
//attach your handler to the reader
reader.setContentHandler(myHandler);
//parse the input InputSource. It will fill your myHandler instance
reader.parse(input);
return myHandler.getPassword();
}
}
The code itself is pretty small, i just inserted some comments for better understanding.
Let me know if you need more help.
Related
I'm trying to parse xml from the code bellow:
XMLParser xmlParser = new XMLParser();
String xml = xmlParser.getXmlFromUrl(URL2);
Document doc = xmlParser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("item");
Element e = (Element) nl.item(0);
that's working properly when URL2 = http://api.androidhive.info/pizza/?format=xml
But when im using my server: URL2 = http://udios.bugs3.com/test.xml it falls in the last line:
NodeList nl = doc.getElementsByTagName("item");
with the following exception:
NullPointerException
Unexpected token (position:TEXT #1:4 in java.io.StringReader#41391770)
The 2 xml files are identical, and i don't thing that the problem is in the server, maybe encoding problem?
I would appreciate if someone will help me
thanks
i think this link is used full...
check this Link
i have shown with only <name>...</name> tag, do the same with <id>...</id> , <cost>...</cost> and <description>...</description>
TextView name[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(URL2);
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
}
MyXMLHandler.java
/* This file is used to handle the XML tags. So we need to extends with DefaultHandler.
we need to override startElement, endElement & characters method .
startElemnt method called when the tag starts.
endElemnt method called when the tag ends
characres method to get characters inside tag.
*/
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>Android</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("menu"))
{
/** Start */
sitesList = new SitesList();
}
}
/** Called when tag closing ( ex:- <name>Android</name>
* -- </name> )*/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("name"))
sitesList.setName(currentValue);
}
/** Called to get tag characters ( ex:- <name>Android</name>
* -- to get Android Character ) */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
SitesList.java
// Contains Getter & Setter Method
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String> name = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
}
found workaround:
took the xml - open with notepad - save as (ANSI)
From the past few days, I have been working on an Android code to call a local web service. I am using ksoap2 libraries for Android "ksoap2-android-assembly-2.5.7-jar-with-dependencies.jar" to call my SOAP web service created in .NET
The issue is that before request for a particular function I need to authenticate a client using basic http request.
This is my code :
public String CallSoapConnexion(String login, String mdp) {
SoapObject request = new SoapObject(nms, mth);
PropertyInfo pi = new PropertyInfo();
pi.setName("login");
pi.setValue(login);
pi.setType(String.class);
request.addProperty(pi);
pi = new PropertyInfo();
pi.setName("mdp");
pi.setValue(mdp);
pi.setType(String.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(urlHttp);
List<HeaderProperty> headerList = new ArrayList<HeaderProperty>();
headerList
.add(new HeaderProperty("Authorization", "Basic "
+ org.kobjects.base64.Base64.encode("login:pasword"
.getBytes())));
Object response = null;
try {
httpTransport.call(act, envelope, headerList);
response = envelope.getResponse();
} catch (Exception ex) {
return ex.toString;
}
return ex.toString;
}
But I get the following Exception :
org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG <html>#2:7 in java.io.InputStreamReader#44f66cb0)
Ksoap2 gave me a lot of trouble, I ended up making my own parser using SAXparser wich is the fastest way to parse XML. This is how I did it.
First in a class I saved all the constant parameter the WebServices will needs. They are all public and static so I can access them anywhere in the project without having to instanciate the class. Let's call it MyConstants.class
//######################## LOGIN WEB SERVICE CONSTANTS
/**
* This string constructs the SOAP Envelope you need to use to Use the DoLogin WebService.
* Use this string with String.format in the following way.
* #param sUserName (String)
* #param sPassword (String)
* #Example String env = String.format(WebserviceConsumer.LOGIN_ENVELOPE, username, password);
* */
public static final String LOGIN_ENVELOPE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<Login xmlns=\"webServiceNamespace\">" +
"<sUsername>%s</sUsername>" +
"<sPassword>%s</sPassword>" +
"</Login>" +
"</soap:Body>" +
"</soap:Envelope>";
public static final String LOGIN_SOAP_ACTION = "webServiceNamespace/Login";
public static final String LOGIN_URL = "https://ws.yoururl.com/YourLoginPage.asmx?op=Login";
public static final int LOGIN = 100;
And this is the parser I "did". It's based on another parser I found, so I don't know if it's perfect, but it works very well.
[EDIT] I changed the parser after some time because SAX parser is not a good way to go. It is fast but it's not efficient, because it creates a lot of objects that then have to be collected by the Garbage Collector. Google recommends to use XMLPullParser to do this job. It's usage is even easier than that of SAX. [/EDIT]
package com.yourproject.parsers;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.os.Bundle;
/**Callback Example
* #example
* <?xml version="1.0" encoding="utf-8"?>
* <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
* xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
* xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
* <soap:Body>
* <LoginResponse xmlns="https://ws.yoururl.com/" >
* <LoginResult>
* <ROOT xmlns="" >
* <PassportKey>
* <Key>653215989827346254362544623544652321</Key>
* <otherLoginInfo>585051</otherLoginInfo>
* </PassportKey>
* </ROOT>
* </LoginResult>
* </LoginResponse>
* </soap:Body>
* </soap:Envelope>
*/
/**
* The loginParser saves the parsed data in a bundle. Once the parsing is done, call the
* getResutl() function to get a bundle that has the login authentication result.
* */
public class LoginParser extends DefaultHandler {
private String foundData = "";
private String authCode = "";
private String otherInfo = "";
private Bundle result;
public synchronized void parse(InputStream is) throws ParserConfigurationException, SAXException, IOException{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(is));
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
foundData += new String(ch, start, length);
}
#Override
public void startDocument() throws SAXException{
// Nothing to do
}
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException{
foundData = "";
}
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException{
if (qName.equals("Key")) {
authCode = foundData;
} else if (qName.equals("otherLoginInfo")){
otherInfo = foundData;
}
}
#Override
public void endDocument() throws SAXException{
// Nothing to do.
}
public Bundle getResult(){
result = new Bundle();
result.putString("authCode", authCode);
result.putString("otherInfo", otherInfo);
return result;
}
}
And now the class that uses the parser. Once you have this you can call this anywhere in the project you like.
package com.yourproject.web;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import com.yourproject.parsers.LoginParser;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
/**
* Public class used to send a SOAP message to our Webservices.
*
* Code from
* http://mobileorchard.com/android-app-development-calling-web-services/
* */
public class WebserviceCall{
LoginParser lp;
[... other parsers ...]
[... other parsers implementation ...]
public Bundle CallWebServiceParseAndReturn(String url, String soapAction, String envelope, int callerRequest) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpRequest = null;
HttpResponse httpResponse = null;
Bundle result = null;
httpRequest = new HttpPost(url);
if (envelope != null) {
httpRequest.setEntity(new StringEntity(envelope));
httpRequest.addHeader("Content-Type", "text/xml; charset=utf-8");
}
httpResponse = httpclient.execute(httpRequest);
switch (callerRequest) {
case MyConstants.LOGIN:
lp = new LoginParser();
lp.parse(httpResponse.getEntity().getContent());
result = lp.getResult();
break;
case MyConstants.OTHERPARSERS:
case default:
break;
return result;
}
}
Finally, here is an example of how you use this in your project.
private void callWebserviceLogin(String userName, String password) {
try{
Bundle result = null;
WebserviceCall wsCall = new WebserviceCall();
String wsEnvelope = String.format(MyConstants.LOGIN_ENVELOPE, userName, password);
result = wsCall.CallWebServiceParseAndReturn(MyConstants.LOGIN_URL, MyConstants.LOGIN_SOAP_ACTION, wsEnvelope, MyConstants.LOGIN);
authenticationResult = result.getString("authCode");
} catch (Exception e) {
authenticationResult = "";
Log.e("Login error", e.getMessage());
}
}
If you see the envelope constant I have, there are some %s marks in the string. When I use String.format, it replaces each mark with the parameter you pass after the first one (wich is the string holding the markers) in order of appearance.
I know this is not what you where expecting, but I hope this helps.
hei guys. i'm quite new in Android programming. I'm trying to get an RSS feed from a website using tutorial i got from the internet. however, when i change the URL to the website id, desired, the program won't show anything and this error appear.
01-13 17:09:30.251: ERROR/RSS Handler IO(277): Too many redirects >> java.net.ProtocolException: Too many redirects
Here is my RSSReader.java page
/**
*
*/
package com.tmm.android.rssreader.reader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.Html;
import android.util.Log;
import com.tmm.android.rssreader.util.Article;
import com.tmm.android.rssreader.util.RSSHandler;
/**
* #author rob
*
*/
public class RssReader {
private final static String BOLD_OPEN = "<B>";
private final static String BOLD_CLOSE = "</B>";
private final static String BREAK = "<BR>";
private final static String ITALIC_OPEN = "<I>";
private final static String ITALIC_CLOSE = "</I>";
private final static String SMALL_OPEN = "<SMALL>";
private final static String SMALL_CLOSE = "</SMALL>";
/**
* This method defines a feed URL and then calles our SAX Handler to read the article list
* from the stream
*
* #return List<JSONObject> - suitable for the List View activity
*/
public static List<JSONObject> getLatestRssFeed(){
//String feed = "http://globoesporte.globo.com/dynamo/futebol/times/vasco/rss2.xml";
String feed = "http://www.flightstats.com/go/rss/flightStatusByRoute.do?guid=34b64945a69b9cac:-420d81e6:134c55649d7:-21c5&departureCode=cgk&arrivalCode=sub&departureDate=2012-01-13";
RSSHandler rh = new RSSHandler();
List<Article> articles = rh.getLatestArticles(feed);
Log.e("RSS ERROR", "Number of articles " + articles.size());
return fillData(articles);
}
/**
* This method takes a list of Article objects and converts them in to the
* correct JSON format so the info can be processed by our list view
*
* #param articles - list<Article>
* #return List<JSONObject> - suitable for the List View activity
*/
private static List<JSONObject> fillData(List<Article> articles) {
List<JSONObject> items = new ArrayList<JSONObject>();
for (Article article : articles) {
JSONObject current = new JSONObject();
try {
buildJsonObject(article, current);
} catch (JSONException e) {
Log.e("RSS ERROR", "Error creating JSON Object from RSS feed");
}
items.add(current);
}
return items;
}
/**
* This method takes a single Article Object and converts it in to a single JSON object
* including some additional HTML formating so they can be displayed nicely
*
* #param article
* #param current
* #throws JSONException
*/
private static void buildJsonObject(Article article, JSONObject current) throws JSONException {
String title = article.getTitle();
String description = article.getDescription();
String date = article.getPubDate();
String imgLink = article.getImgLink();
StringBuffer sb = new StringBuffer();
sb.append(BOLD_OPEN).append(title).append(BOLD_CLOSE);
sb.append(BREAK);
sb.append(description);
sb.append(BREAK);
sb.append(SMALL_OPEN).append(ITALIC_OPEN).append(date).append(ITALIC_CLOSE).append(SMALL_CLOSE);
current.put("text", Html.fromHtml(sb.toString()));
current.put("imageLink", imgLink);
}
}
here is my RSSHandler.java code
package com.tmm.android.rssreader.util;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class RSSHandler extends DefaultHandler {
// Feed and Article objects to use for temporary storage
private Article currentArticle = new Article();
private List<Article> articleList = new ArrayList<Article>();
// Number of articles added so far
private int articlesAdded = 0;
// Number of articles to download
private static final int ARTICLES_LIMIT = 20;
//Current characters being accumulated
StringBuffer chars = new StringBuffer();
/*
* This method is called everytime a start element is found (an opening XML marker)
* here we always reset the characters StringBuffer as we are only currently interested
* in the the text values stored at leaf nodes
*
* (non-Javadoc)
* #see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();
}
/*
* This method is called everytime an end element is found (a closing XML marker)
* here we check what element is being closed, if it is a relevant leaf node that we are
* checking, such as Title, then we get the characters we have accumulated in the StringBuffer
* and set the current Article's title to the value
*
* If this is closing the "Item", it means it is the end of the article, so we add that to the list
* and then reset our Article object for the next one on the stream
*
*
* (non-Javadoc)
* #see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("title"))
{
Log.d("LOGGING RSS XML", "Setting article title: " + chars.toString());
currentArticle.setTitle(chars.toString());
}
else if (localName.equalsIgnoreCase("description"))
{
Log.d("LOGGING RSS XML", "Setting article description: " + chars.toString());
currentArticle.setDescription(chars.toString());
}
else if (localName.equalsIgnoreCase("pubDate"))
{
Log.d("LOGGING RSS XML", "Setting article published date: " + chars.toString());
currentArticle.setPubDate(chars.toString());
}
else if (localName.equalsIgnoreCase("encoded"))
{
Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
currentArticle.setEncodedContent(chars.toString());
}
//////////////////
else if(localName.equalsIgnoreCase("fh:FlightHistory"))
{
Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
currentArticle.setFhFlightHistory(chars.toString());
}
else if(localName.equalsIgnoreCase("fh:Airline"))
{
Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
currentArticle.setFhAirline(chars.toString());
}
////////////////////
else if (localName.equalsIgnoreCase("item"))
{
}
else if (localName.equalsIgnoreCase("link"))
{
try {
System.out.println(chars.toString());
Log.d("LOGGING RSS XML", "Setting article link url: " + chars.toString());
currentArticle.setUrl(new URL(chars.toString()));
} catch (MalformedURLException e) {
Log.e("RSA Error", e.getMessage());
e.printStackTrace();
}
}
// Check if looking for article, and if article is complete
if (localName.equalsIgnoreCase("item")) {
articleList.add(currentArticle);
currentArticle = new Article();
// Lets check if we've hit our limit on number of articles
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT)
{
throw new SAXException();
}
}
}
/*
* This method is called when characters are found in between XML markers, however, there is no
* guarante that this will be called at the end of the node, or that it will be called only once
* , so we just accumulate these and then deal with them in endElement() to be sure we have all the
* text
*
* (non-Javadoc)
* #see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
/**
* This is the entry point to the parser and creates the feed to be parsed
*
* #param feedUrl
* #return
*/
public List<Article> getLatestArticles(String feedUrl) {
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
} catch (SAXException e) {
Log.e("RSS Handler SAX", e.toString());
} catch (ParserConfigurationException e) {
Log.e("RSS Handler Parser Config", e.toString());
}
return articleList;
}
}
Please, any answer and suggest will be so much appreciated. :)
It is most likely a user-agent related problem.
As far as I see it, the site you are calling has a special version for mobiles, and won't give you the RSS feed if it detects that you are using a mobile user agent.
You probably need to change it.
I am new in android. I want to create a application to read the XML file from an URL and show the image in a grid view using ImageUrl of image.
Thanks for the answer but I am able to read xml file from url but I need if in xml imageUrl is there so show in grid view.
This is my xml file
<?xml version="1.0" encoding="UTF-8"?>
<channels>
<channel>
<name>ndtv</name>
<logo>http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png</logo>
<description>this is a news Channel</description>
<rssfeed>ndtv.com</rssfeed>
</channel>
<channel>
<name>star news</name>
<logo>http://a3.twimg.com/profile_images/740897825/AndroidCast-350_normal.png</logo>
<description>this is a news Channel</description>
<rssfeed>starnews.com</rssfeed>
</channel>
</channels>
Check the following URl to kow about XML parsers
http://www.totheriver.com/learn/xml/xmltutorial.html#6.2
First get the data from url. store in in file. use the folowing code to parse the XML using SAXParser
SAX Parser to parse an XML
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserExample extends DefaultHandler{
List myEmpls;
private String tempVal;
//to maintain context
private Employee tempEmp;
public SAXParserExample(){
myEmpls = new ArrayList();
}
public void runExample() {
parseDocument();
printData();
}
private void parseDocument() {
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//parse the file and also register this class for call backs
sp.parse("employees.xml", this);
}catch(SAXException se) {
se.printStackTrace();
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch (IOException ie) {
ie.printStackTrace();
}
}
/**
* Iterate through the list and print
* the contents
*/
private void printData(){
System.out.println("No of Employees '" + myEmpls.size() + "'.");
Iterator it = myEmpls.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
//Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//reset
tempVal = "";
if(qName.equalsIgnoreCase("Employee")) {
//create a new instance of employee
tempEmp = new Employee();
tempEmp.setType(attributes.getValue("type"));
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch,start,length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("Employee")) {
//add it to the list
myEmpls.add(tempEmp);
}else if (qName.equalsIgnoreCase("Name")) {
tempEmp.setName(tempVal);
}else if (qName.equalsIgnoreCase("Id")) {
tempEmp.setId(Integer.parseInt(tempVal));
}else if (qName.equalsIgnoreCase("Age")) {
tempEmp.setAge(Integer.parseInt(tempVal));
}
}
public static void main(String[] args){
SAXParserExample spe = new SAXParserExample();
spe.runExample();
}
}
Working with XML on Android
Grid View example
I've got a custom contentHandler (called XMLHandler), I've been to a lot of sites via Google and StackOverflow that detail how to set that up.
What I do not understand is how to USE it.
Xml.parse(...,...) returns nothing, because it is a void method.
How do I access my parsed XML data?
I realize this question is probably trivial, but I've been searching for (literally) hours and have found no solution.
Please help.
String result = fetchData(doesntmatter);
Xml.parse(result, new XMLHandler());
Here is one example i hope it will be usefull to understand "SAXParser"
package test.example;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class XMLParsingDemo extends Activity {
private final String MY_DEBUG_TAG = "WeatherForcaster";
/** 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);
try {
/* Create a URL we want to load some xml-data from. */
DefaultHttpClient hc = new DefaultHttpClient();
ResponseHandler <String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
String response=hc.execute(postMethod,res);
/* 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. */
InputSource inputSource = new InputSource();
inputSource.setEncoding("UTF-8");
inputSource.setCharacterStream(new StringReader(response));
/* Parse the xml-data from our URL. */
xr.parse(inputSource);
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
tv.setText(response + "\n\n\n***************************************" + parsedExampleDataSet.toString());
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
}
/* Display the TextView. */
this.setContentView(tv);
}
public class ExampleHandler extends DefaultHandler {
// ===========================================================
// Fields
// ===========================================================
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_mytag = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException {
super.startElement(uri, localName, qName, atts);
if (localName.equals("outertag")) {
this.in_outertag = true;
}
else if (localName.equals("innertag")) {
String attrValue = atts.getValue("sampleattribute");
myParsedExampleDataSet.setExtractedString(attrValue);
this.in_innertag = true;
}
else if (localName.equals("mytag")) {
this.in_mytag = true;
}
else if (localName.equals("tagwithnumber")) {
// Extract an Attribute
String attrValue = atts.getValue("thenumber");
int i = Integer.parseInt(attrValue);
myParsedExampleDataSet.setExtractedInt(i);
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = false;
}else if (localName.equals("innertag")) {
this.in_innertag = false;
}else if (localName.equals("mytag")) {
this.in_mytag = false;
}else if (localName.equals("tagwithnumber")) {
// Nothing to do here
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_mytag){
myParsedExampleDataSet.setExtractedString(new String(ch));
}
}
}
public class ParsedExampleDataSet {
private String extractedString = null;
private int extractedInt = 0;
public String getExtractedString() {
return extractedString;
}
public void setExtractedString(String extractedString) {
this.extractedString = extractedString;
}
public int getExtractedInt() {
return extractedInt;
}
public void setExtractedInt(int extractedInt) {
this.extractedInt = extractedInt;
}
public String toString(){
return "\n\n\nExtractedString = " + this.extractedString
+ "\n\n\nExtractedInt = " + this.extractedInt;
}
}
}
You have to access your XML data into handler which you have define by XMLHandler()
you have to override
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException {
}
#Override
public void endElement(String namespaceURI, String localName, String qName) {
}
and
#Override
public void characters(char ch[], int start, int length) {
}