Android SAXParser for xml Parsing - android

I'm trying to Parse the below xml file:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel >
<title>TORi : Hosts Profiles</title>
<link>http://www.teugadio.com</link>
<description>TRi : TelOne Rdio Hots Prfiles</description>
<dc:language>en-us</dc:language>
<dc:rights>Copyright #copy; 2000-11, teluone.com, All Rights Reserved..</dc:rights>
<dc:date>2013-04-14T23:07:55+01:00</dc:date>
<dc:creator>TORi : TeluguOne Radio</dc:creator>
<dc:subject>TORi : TeluguOne Radio</dc:subject>
<item >
<title>Rajesh </title>
<link>http://www.teluradio.com/rssHstDescr.php?hostId=146</link>
<guid isPermaLink="false">http://www.telugeradio.com/rssHostDescr.php?hostId=146</guid>
<pubDate>2013-04-12</pubDate>
<description>Rajesh</description>
<media:thumbnail width='66' height='49' url='http://hostphotos/Rajh-Photo.jpg'></media:thumbnail>
</item>
<item >
<title>Prasanthi </title>
<link>http://www.tuguonadio.com/rssHostDescr.php?hostId=145</link>
<guid isPermaLink="false">http://www.telugadio.com/rsHostDescr.php?hostId=145</guid>
<pubDate>2013-04-10</pubDate>
<description>Prasanthi</description>
<media:thumbnail width='66' height='49' url='http://hostphotos/Pri-image.jpg'></media:thumbnail>
</item>
etc.......
</channel>
</rss>
I'm able to Parse the Data and my OutPut is:
TITLE TORi : Hosts Profiles
TITLE http://www.teluguoneradio.com
TITLE TORi : TeluguOne Radio Hosts Profiles
TITLE en-us
TITLE Copyright #copy; 2000-11, teluguone.com, All Rights Reserved..
TITLE 2013-04-14T23:31:24+01:00
TITLE TORi : TeluguOne Radio
TITLETORi : TeluguOne Radio
TITLE Rajesh
TITLE Prasanthi
TITLE Maireyi Ganaaju
etc..........
But ,I want to get the details with in the Item Tag itself?Could any one tell me what Should i Change in my Code?
My Required Output is:
TITLE Rajesh
TITLE Prasanthi
TITLE Maireyi Ganaaju
etc..........
Here My Code:
import static com.tort.BaseFeedParser.ITEM;
import static com.tort.BaseFeedParser.LINK;
import static com.tort.BaseFeedParser.TITLE;
import static com.tort.BaseFeedParser.PUBDATE;
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 HostsRssHandler extends DefaultHandler {
private List<HostsProfile> messages;
private HostsProfile currentMessage;
private StringBuilder builder;
public List<HostsProfile> getMessages(){
return messages;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
builder.append(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
if (this.currentMessage != null){
if (localName.equalsIgnoreCase(TITLE)){
currentMessage.setTitle(builder.toString());
} else if (localName.equalsIgnoreCase(LINK)){
currentMessage.setLink(builder.toString());
}
else if (localName.equalsIgnoreCase(PUBDATE)){
currentMessage.setDate(builder.toString());
}
else if (localName.equalsIgnoreCase(ITEM)){
messages.add(currentMessage);
}
builder.setLength(0);
}
}
#Override
public void startDocument() throws SAXException {
super.startDocument();
messages = new ArrayList<HostsProfile>();
builder = new StringBuilder();
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase(ITEM)){
this.currentMessage = new HostsProfile();
}
if (localName.equalsIgnoreCase("thumbnail")) {
currentMessage.setMediathumbnail(attributes.getValue("url"));
}
}
}

How about adding a boolean flag insideItem?
public class HostsRssHandler extends DefaultHandler {
private boolean insideItem;
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
if (this.currentMessage != null && insideItem){
if (localName.equalsIgnoreCase(TITLE)){
currentMessage.setTitle(builder.toString());
} else if (localName.equalsIgnoreCase(LINK)){
currentMessage.setLink(builder.toString());
} else if (localName.equalsIgnoreCase(PUBDATE)){
currentMessage.setDate(builder.toString());
} else if (localName.equalsIgnoreCase(ITEM)){
messages.add(currentMessage);
insideItem = false;
}
builder.setLength(0);
}
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase(ITEM)){
this.currentMessage = new HostsProfile();
insideItem = true;
} else if (localName.equalsIgnoreCase("thumbnail") && insideItem) {
currentMessage.setMediathumbnail(attributes.getValue("url"));
}
}
}

Related

Can't fetch all text when parse from google alerts

I already made an Android RSS Feed App from Google Alerts Source. After I compiled and running only showing about half article or can't fetch all text from one source but not crash.
From RssAtomParseHandler.java
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.a.b.c.d.e.RssAtomItem;
public class RssAtomParseHandler extends DefaultHandler {
private List<RssAtomItem> rssItems;
// Used to reference item while parsing
private RssAtomItem currentItem;
// Parsing title indicator
private boolean parsingTitle;
// Parsing link indicator
private boolean parsingContents;
// A buffer for title contents
private StringBuffer currentTitleSb;
// A buffer for content tag contents
private StringBuffer currentContentSb;
public RssAtomParseHandler() {
rssItems = new ArrayList<RssAtomItem>();
}
public List<RssAtomItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("entry".equals(qName)) {
currentItem = new RssAtomItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
currentTitleSb = new StringBuffer();
} else if ("content".equals(qName)) {
parsingContents = true;
currentContentSb = new StringBuffer();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("entry".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
if (currentItem != null) // There is a title tag for a whole channel present. It is being parsed before the entry tag is present, so we need to check if item is not null
currentItem.setTitle(currentTitleSb.toString());
} else if ("content".equals(qName)) {
parsingContents = false;
if (currentItem != null)
currentItem.setContent(currentContentSb.toString());
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (parsingTitle) {
if (currentItem != null)
currentTitleSb.append(new String(ch, start, length));
} else if (parsingContents) {
if (currentItem != null)
currentContentSb.append(new String(ch, start, length));
}
} }
From RssAtomReader.java
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.a.b.c.d.e.RssAtomItem;
public class RssAtomReader {
private String rssUrl;
/**
* Constructor
*
* #param rssUrl
*/
public RssAtomReader(String rssUrl) {
this.rssUrl = rssUrl;
}
/**
* Get RSS items.
*
* #return
*/
public List<RssAtomItem> getItems() throws Exception {
// SAX parse RSS data
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
RssAtomParseHandler handler = new RssAtomParseHandler();
saxParser.parse(rssUrl, handler);
return handler.getItems();
} }
From activity_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/detailsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[POST TITLE GOES HERE]"
android:textAppearance="?android:attr/textAppearanceMedium" />
<WebView
android:id="#+id/detailsWebView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
How I can fix it so it will show ?

How to parse xml for HTTPS url using SAXParser in Android

URL url = new URL("https://www.setindia.com");
URLConnection urlConnectionObject = url.openConnection();
xmlHandlerObject = new XMLHandler();
xmlReaderObject.setContentHandler(xmlHandlerObject);
xmlReaderObject.parse(new InputSource(urlConnectionObject.getInputStream()));
// error on the last line please get me an explanation (new to android) and is this right
MAIN ACTIVITY:
package com.example.testparser;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
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.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
public static String TAG = "MYParser";
GettersSetters getData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate");
View layout = findViewById(R.id.layout);
TextView tittle[];
TextView country[];
XMLHandler xmlHandlerObject = null;
try{
Log.d(TAG, "try");
SAXParserFactory saxParserFactoryObject = SAXParserFactory.newInstance(); //obtain and configure a SAX based parser
SAXParser saxParserObject = saxParserFactoryObject.newSAXParser(); //obtaining object for SAX parser
XMLReader xmlReaderObject = saxParserObject.getXMLReader();
URL url = new URL("https://www.setindia.com/setindia_api/episode/1?date=22-10-2013&hd=1");
URLConnection urlConnectionObject = url.openConnection();
xmlHandlerObject = new XMLHandler();
xmlReaderObject.setContentHandler(xmlHandlerObject);
Log.d(TAG, "about to get an error");
xmlReaderObject.parse(new InputSource(urlConnectionObject.getInputStream()));
Log.d(TAG, "try end");
}
catch (Exception e) {
Log.e(TAG, e.getMessage());
}
Log.d(TAG, "OnCreate fetching the data from the xml");
getData = xmlHandlerObject.getXMLData();
tittle = new TextView[getData.getTittle().size()];
country = new TextView[getData.getCountry().size()];
for (int i = 0; i < getData.getTittle().size(); i++) {
tittle[i] = new TextView(this);
tittle[i].setText("ITEM is : " + getData.getTittle().get(i));
country[i] = new TextView(this);
country[i].setText("Country is :" + getData.getTittle().get(i));
((ViewGroup) layout).addView(tittle[i]);
((ViewGroup) layout).addView(country[i]);
setContentView(R.layout.main);
}
}
#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;
}
}
GettersSetters :
package com.example.testparser;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.util.Log;
public class GettersSetters {
private ArrayList<String> tittle = new ArrayList<String>();
private ArrayList<String> country = new ArrayList<String>();
public ArrayList<String> getCountry(){
return country;
}
public ArrayList<String> getTittle(){
return tittle;
}
public void setCountry(String country){
this.country.add(country);
Log.i("This is the country : ",country);
}
public void setTittle(String tittle){
this.tittle.add(tittle);
Log.i("This is the tittle : ",tittle);
}
}
XMLHandler:
package com.example.testparser;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
public static String TAG = "MYParser";
public static GettersSetters data = null;
String elementValue = null ;
Boolean elementOn = false;
public GettersSetters getXMLData(){
Log.e(TAG, "getXMLdata -> "+data.toString());
return data;
}
public void setXMLData(GettersSetters data){
XMLHandler.data = data;
Log.e(TAG, "setXmldata");
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
elementOn = true;
Log.d(TAG, "Checking the first element"+localName.equalsIgnoreCase("item"));
if(localName.equalsIgnoreCase("item"))
{
Log.d(TAG, "Creating a new getter setter instance");
data = new GettersSetters();
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if(elementOn)
{
elementValue = new String(ch,start,length);
elementOn =false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
super.endElement(uri, localName, qName);
if(localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
if(localName.equalsIgnoreCase("tittle"))
data.setTittle(elementValue);
}
}
MAIN.Xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SAGAR HERE"
android:textSize="20dp"
android:gravity="center_horizontal"
android:id="#+id/layout"
/>
</LinearLayout>
Don't do network operations on UI Thread (main).
You can use AsyncTask which enables proper and easy use of the UI thread. it allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers (It uses an inner thread pool). See more at: AsyncTask API

Android - Trouble parsing enclosure tag in XML

I am using the following code to parse an XML file. Everything works fine except when I try to read the url attribute from the enclosure tag. Everything I've read shows to use attributes.getValue("url") but I still seem to get a null value back. Perhaps I'm not returning it correctly?
The specific line I'm trying to parse is like this:
This is the only info I see in LogCat when I try to play the mp3 using a button.
I/StagefrightPlayer( 33): setDataSource('')
E/MediaPlayer( 275): start called in state 4
E/MediaPlayer( 275): error (-38, 0)
E/MediaPlayer( 275): Error (-38,0)
The lines I believe are causing the problem are at the bottom:
else if (localName.equalsIgnoreCase(ENC)) {
String link = attributes.getValue("url");
currentMessage.setEnc(link);
Thanks.
package com.Demo;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import static com.Demo.BaseFeedParser.*;
public class RssHandler extends DefaultHandler{
private List<Message> messages;
private Message currentMessage;
private StringBuilder builder;
public List<Message> getMessages(){
return this.messages;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
builder.append(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
if (this.currentMessage != null){
if (localName.equalsIgnoreCase(TITLE)){
currentMessage.setTitle(builder.toString());
} else if (localName.equalsIgnoreCase(LINK)){
currentMessage.setLink(builder.toString());
} else if (localName.equalsIgnoreCase(DESCRIPTION)){
currentMessage.setDescription(builder.toString());
} else if (localName.equalsIgnoreCase(PUB_DATE)){
currentMessage.setDate(builder.toString());
} else if (localName.equalsIgnoreCase(SUMMARY)) {
currentMessage.setSummary(builder.toString());
} else if (localName.equalsIgnoreCase(ITEM)){
messages.add(currentMessage);
builder.setLength(0);
}
}
}
#Override
public void startDocument() throws SAXException {
super.startDocument();
messages = new ArrayList<Message>();
builder = new StringBuilder();
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase(ITEM)){
this.currentMessage = new Message();
}
else if (localName.equalsIgnoreCase(ENC)) {
String link = attributes.getValue("url");
currentMessage.setEnc(link);
}
}
}
This call
String link = attributes.getValue("url");
needs the argument to be the XML qualified (prefixed) name, and "url" may just be the local name.
To debug this, you might look at all attributes using getLength() to figure out how many there are and then use getLocalName(int index) and getQName(int index) to show the different forms of the names.
I have found the answer for XmlPullParser
if (tagName.equalsIgnoreCase("enclosure")) {
String imgUrl = parser.getAttributeValue(null, "url");
article.setImageUrl(imgUrl);

Problem in SAX parser

i need to get information from xml file.
my problem is i cant get proper response from xml file
package com.xmlparser;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class xmlparser extends Activity {
/** Called when the activity is first created. */
detaset dt=null;
detaset Date;
ArrayList<String> Score;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
URL url = new URL("C://Users//nik//Desktop//a.xml");
System.out.println(url);
TextView tv = new TextView(this);
/* 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*/
Handler myExampleHandler = new Handler();
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. */
detaset parsedExampleDataSet = myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
System.out.println(parsedExampleDataSet.toString());
// Date = myExampleHandler.getParsedData();
//System.out.println(Date);
this.setContentView(tv);
}catch (Exception e) {
e.printStackTrace();
}
}
// TODO: handle exception
/* Display the TextView. */
}
package com.xmlparser;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class Handler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private boolean NewDataSet = false;
private boolean Table = false;
private boolean Date = false;
private boolean Score = false;
private detaset myParsedExampleDataSet = new detaset();
// ===========================================================
// Getter & Setter
// ===========================================================
public detaset getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new detaset();
}
#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 namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("NewDataSet")) {
this.NewDataSet = true;
}else if (localName.equals("Table")) {
this.Table = true;
}else if (localName.equals("Date")) {
this.Date = true;
}else if (localName.equals("Score")) {
// Extract an Attribute
this.Score = true;
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("NewDataSet")) {
this.NewDataSet = false;
System.out.println("Newdataset"+NewDataSet);
}else if (localName.equals("Table")) {
this.Table = false;
System.out.println("Table"+Table);
}else if (localName.equals("Date")) {
this.Date = false;
}else if (localName.equals("Score")) {
// Nothing to do here
this.Score = false;
System.out.println("Score"+Score);
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.Date){
myParsedExampleDataSet.setDate(new String(ch, start, length));
}
if(this.Score){
myParsedExampleDataSet.setScore(new String(ch, start, length));
}
}
}
package com.xmlparser;
public class detaset {
private String Date = null;
private String Score = null;
public void setDate(String Date) {
this.Date = Date;
}
public String getDate()
{
return Date;
}
public void setScore(String Score) {
this.Score = Score;
}
public String getScore()
{
return Score;
}
}
<?xml version="1.0" encoding="utf-8" ?>
- <DataSet xmlns="http://tempuri.org/">
- <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
- <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
- <xs:complexType>
- <xs:choice minOccurs="0" maxOccurs="unbounded">
- <xs:element name="Table">
- <xs:complexType>
- <xs:sequence>
<xs:element name="Date" type="xs:string" minOccurs="0" />
<xs:element name="Score" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
- <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
- <NewDataSet xmlns="">
- <Table diffgr:id="Table1" msdata:rowOrder="0">
<Date>12/5/2011</Date>
<Score>5</Score>
</Table>
- <Table diffgr:id="Table2" msdata:rowOrder="1">
<Date>45/5/2011</Date>
<Score>54</Score>
</Table>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
I think the mistake is in the line URL url = new URL("C://Users//nik//Desktop//a.xml");
You will run the program in emulator or in device there is no such path in either device or emulator. You can put the xml file in assets and read the file from there.
Donot forget to vote if my response is helpful for you.
Thanks

local parser problem in android

i am make a 3 file that parse "a.xml",problem is as a result i got last line not entire parsing.
so can you help me?
package barc3.barc3;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class barc3 extends Activity {
private TextView orgXmlTxt;
private TextView parsedXmlTxt;
private Button parseBtn,chartbtn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
try {
setContentView(R.layout.main);
orgXmlTxt = (TextView) findViewById(R.id.orgXMLTxt);
parsedXmlTxt = (TextView) findViewById(R.id.parsedXMLTxt);
parseBtn = (Button) findViewById(R.id.parseBtn);
chartbtn =(Button) findViewById(R.id.chartbtn);
//orgXmlTxt.setText(getOriginalMyXML());
parseBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
parsedXmlTxt.setText(getParsedMyXML());
} catch (Exception e) {
// TODO Auto-generated catch block
orgXmlTxt.setText(e.getMessage());
}
}
});
chartbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(barc3.this,XMLParsingDemo.class));
}
});
} catch (Exception e) {
orgXmlTxt.setText(e.getMessage());
}
}
/**
* This method is called by OnCreate during startup to show the original XML file content
* #return
* #throws Exception
*/
private String getOriginalMyXML() throws Exception {
/* Load xml file being shown from raw resource folder */
InputStream in = this.getResources().openRawResource(R.raw.a);
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
in.close();
return inLine.toString();
}
private String getParsedMyXML() throws Exception {
StringBuffer inLine = new StringBuffer();
/* 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 */
XMLHandler myExampleHandler = new XMLHandler();
xr.setContentHandler(myExampleHandler);
/* Load xml file from raw folder*/
InputStream in = this.getResources().openRawResource(R.raw.a);
/* Begin parsing */
xr.parse(new InputSource(in));
XMLDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
String s = parsedExampleDataSet.getDate();
String s2 = parsedExampleDataSet.getScore();
System.out.println("s is:::::: "+s);
System.out.println("s2 is :::::"+s2);
System.out.println(parsedExampleDataSet);
inLine.append(parsedExampleDataSet.toString());
in.close();
return inLine.toString();
}
}
package barc3.barc3;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private boolean NewDataSet = false;
private boolean Table = false;
private boolean Date = false;
private boolean Score = false;
private XMLDataSet myParsedExampleDataSet = new XMLDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public XMLDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new XMLDataSet();
}
#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 namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("NewDataSet")) {
this.NewDataSet = true;
}else if (localName.equals("Table")) {
this.Table = true;
}else if (localName.equals("Date")) {
this.Date = true;
}
else if (localName.equals("Score")) {
this.Score = true;
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("NewDataSet")) {
this.NewDataSet = false;
}else if (localName.equals("Table")) {
this.Table = false;
}else if (localName.equals("Date")) {
this.Date = false;
}
else if (localName.equals("Score")) {
this.Score = false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.Date)
{
myParsedExampleDataSet.setDate(new String(ch, start, length));
System.out.println("Date"+Date);
}
if(this.Score)
{
myParsedExampleDataSet.setScore(new String(ch, start, length));
System.out.println("Score"+Score);
}
}
}
package barc3.barc3;
public class XMLDataSet {
String Date = null;
String Score = null;
public String getDate() {
return Date;
}
public void setDate(String Date) {
this.Date = Date;
}
public String getScore() {
return Score;
}
public void setScore(String Score) {
this.Score = Score;
}
public String toString(){
return "Date is = " + this.Date
+ "\nScore is = " + this.Score;
}
}
<?xml version="1.0" encoding="utf-8" ?>
<DataSet xmlns="http://tempuri.org/">
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
- <xs:complexType>
- <xs:choice minOccurs="0" maxOccurs="unbounded">
- <xs:element name="Table">
- <xs:complexType>
- <xs:sequence>
<xs:element name="Date" type="xs:string" minOccurs="0" />
<xs:element name="Score" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
<Table diffgr:id="Table1" msdata:rowOrder="0">
<Date>12/5/2011</Date>
<Score>5</Score>
</Table>
- <Table diffgr:id="Table2" msdata:rowOrder="1">
<Date>45/5/2011</Date>
<Score>54</Score>
</Table>
- <Table diffgr:id="Table3" msdata:rowOrder="2">
<Date>12/5/2011</Date>
<Score>12</Score>
</Table>
- <Table diffgr:id="Table4" msdata:rowOrder="3">
<Date>3/4/2011</Date>
<Score>25</Score>
</Table>
- <Table diffgr:id="Table5" msdata:rowOrder="4">
<Date>6/8/2011</Date>
<Score>45</Score>
</Table>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
The Problem is in your DefaultHandler-class:
myParsedExampleDataSet.setDate(new String(ch, start, length))
The characters-method can be called multiple times on one Tag, for example if this Tag contains entity's like > for a >.
You should use a StringBuilder in this method, so you can append all the new content to it and then get your String using the toString()-method.

Categories

Resources