I am making an application for Android and I need to display an XML file of this page: In the application show Compra="481.3" Venta="485" but i cant "DOLAR SPOT INTERBANCARIO" and Var_por="-0,53" Var_pes="-2,60" hora="10:35". Help me with the code please.
XML image
This is ExampleHandler code
public class ExampleHandler extends DefaultHandler {
private boolean in_Root = false;
private boolean in_Registro = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
}
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("Root")) {
this.in_Root = true;
}else if (localName.equals("Registro")) {
this.in_Registro = true;
// Extract an Attribute
String attrValue = atts.getValue("Compra");
Float compra = Float.parseFloat(attrValue);
myParsedExampleDataSet.setExtractedCompra(compra);
String attrValue2 = atts.getValue("Venta");
Float venta = Float.parseFloat(attrValue2);
myParsedExampleDataSet.setExtractedVenta(venta);
**String attrValue3 = atts.getValue("Var_por");
Float por = Float.parseFloat(attrValue3);
myParsedExampleDataSet.setExtractedPor(por);**
//its my wrong code for Var_por
}
}
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("Root")) {
this.in_Root = false;
}else if (localName.equals("Registro")) {
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_Registro){
//myParsedExampleDataSet.setExtractedStruct(new String(ch, start, length));
}
}
}
You might check out SimpleXML for something small like that. It works well on Android.
SimpleXML parser
I implemented a solution to this problem recently using Jsoup.
The solution outlined below will both fetch the data from the supplied URL and parse it into an array of Strings.
Setup
The .jar file can be found here.
Instructions on how to include it in an Android app are here.
Implementation
Imports used:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
Function code:
public static ArrayList<String> parseDocument()
{
ArrayList<String> values = new ArrayList<String>();
Document doc;
try {
doc = Jsoup.connect("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=7009").get(); // Timeout is in milliseconds
Elements nodes = doc.select("Registro");
values.add( nodes.attr("tipo") );
values.add( nodes.attr("Compra") );
values.add( nodes.attr("Venta") );
values.add( nodes.attr("Var_por") );
// etc
} catch (IOException e) {
e.printStackTrace();
}
return values;
}
All you need to do once the function is returned is read the values from the ArrayList.
Related
Here is my xml,
<root>
<child>
<Lunchmenu>
<id>2</id>
<lunch_date>2013-10-24</lunch_date>
<break_name>Lunch</break_name>
<class_id/>
<school_id>1</school_id>
<batch_id/>
</Lunchmenu>
<Eatable>
<id>2</id>
<eatable_name>Apples</eatable_name>
</Eatable>
</child>
<child>
<Lunchmenu>
<id>2</id>
<lunch_date>2013-10-24</lunch_date>
<break_name>Lunch</break_name>
<class_id/>
<school_id>1</school_id>
<batch_id/>
</Lunchmenu>
<Eatable>
<id>3</id>
<eatable_name>Orange</eatable_name>
</Eatable>
</child>
I need to know that, is there any way to parse above xml's child as there are again two separate tags like Lunchmenu and eatable.
I am using sax parser to parse this xml.
I know how to parse single child tag having data and again its iteration, but here I am confused how to do it?
please suggest any solution if anyone knows How to parse it??
thank you
and my parser class is :
SchoolParser.java
public class SchoolParser extends DefaultHandler {
private List<School> schoolListData ;
private boolean isSuccess;
private School school;
StringBuilder tempData;
#Override
public void startDocument() throws SAXException {
super.startDocument();
Log.e("StudentListParser","startDocument");
schoolListData = new ArrayList<School>();
}
public List<School> getSchoolListData(){
return schoolListData;
}
#Override
public void startElement(String uri, String localName, String qName,
org.xml.sax.Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equals("School")) {
school = new School();
Log.e("SchoolParser", "-----START----");
}
tempData = new StringBuilder();
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempData.append(new String(ch, start, length));
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(localName.equals("School")){
schoolListData.add(school);
Log.d("localName",localName);
}
else if (localName.equals("id")) {
Log.e("id", localName);
school.id = Integer.parseInt(tempData.toString());
} else if (localName.equals("school_name")) {
school.schoolName = tempData.toString();
Log.e("name", localName);
} else if (localName.equals("logo")) {
school.logo = tempData.toString().getBytes();
Log.e("logo", localName);
}else if (localName.equals("phone")) {
school.phn_no = tempData.toString();
Log.e("phn no", localName);
}
else if (localName.equals("School")) {
Log.e("SchoolParser", "----END---");
}
// int size = buffer.length();
// buffer.delete(0, size);
// Log.i("buffer is empty", ""+buffer.toString());
}
#Override
public void endDocument() throws SAXException {
super.endDocument();
isSuccess = false;
Log.e("StudentListParser", "endDocument");
}
}
May be you can use serialize logic to parse xml to direct java class object.
You can use below class..
package com.lib.android.util;
import java.io.InputStream;
import org.apache.log4j.Logger;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import com.lib.android.util.logger.PLogger;
public class XmlParser
{
private static Logger log = new PLogger(XmlParser.class).getLogger();
public static Object Parse(Class<? extends Object> parseInto, InputStream is)
{
Serializer serializer = new Persister();
try
{
Object obj = serializer.read(parseInto, is);
return obj;
} catch (Exception e)
{
log.error(e.getMessage());
}
return null;
}
}
Hope it will help you..
I'm new in Android (and in Java too) but now I'm starting to work with web services.
So to understand better how to parse an XML, I started to try this tutorial:
http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html
With the XML used in this example:
<outertag>
<innertag sampleattribute="innertagAttribute">
<mytag>anddev.org rulez =)</mytag>
<tagwithnumber thenumber="1337"/>
</innertag>
</outertag>
I understand how it works (I guess), but if the XML is like this:
<outertag>
<innertag sampleattribute="innertagAttribute">
<mytag>anddev.org rulez =)</mytag>
<tagwithnumber thenumber="1337"/>
</innertag>
<innertag sampleattribute="innertagAttribute2">
<mytag>something</mytag>
<tagwithnumber thenumber="14214"/>
</innertag>
</outertag>
What needs to change in the classes of the application to obtain the data of the various elements?
I appreciate any sugestion...
Full source code:
ParseXML.java
package org.anddev.android.parsingxml;
import java.net.URL;
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.widget.TextView;
public class ParsingXML 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. */
URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
xr.parse(new InputSource(url.openStream()));
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedExampleDataSet parsedExampleDataSet =
myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
tv.setText(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);
}
}
ExampleHandler
package org.anddev.android.parsingxml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
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 namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = true;
}else if (localName.equals("innertag")) {
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, start, length));
}
}
}
ParsedExampleDataSet
package org.anddev.android.parsingxml;
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 "ExtractedString = " + this.extractedString
+ "nExtractedInt = " + this.extractedInt;
}
}
Problem solved!
Bellow are the sites with useful information:
https://stackoverflow.com/a/4828765
https://stackoverflow.com/a/5709544
http://as400samplecode.blogspot.com/2011/11/android-parse-xml-file-example-using.html
http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html
My initial problem was how I should define the class for the data which I wanted to extract from XML. After I figured out how I should do this (reviewing the basic concepts of JAVA programming), I changed the type of data returned by the ExampleHandler to an ArrayList<"class of the data you want return">.
I give below an example:
Example of a XML you want to parse:
<outertag>
<cartag type="Audi">
<itemtag name="model">A4</itemtag>
<itemtag name="color">Black</itemtag>
<itemtag name="year">2005</itemtag>
</cartag>
<cartag type="Honda">
<itemtag name="model">Civic</itemtag>
<itemtag name="color">Red</itemtag>
<itemtag name="year">2001</itemtag>
</cartag>
<cartag type="Seat">
<itemtag name="model">Leon</itemtag>
<itemtag name="color">White</itemtag>
<itemtag name="year">2009</itemtag>
</cartag>
</outertag>
So here you should define a class "car" with proper attributes (String type, model, color, year;), setters and getters...
My suggestion of ExampleHandler for this XML is:
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private int numberOfItems=3;
private boolean in_outertag = false;
private boolean in_cartag = false;
private boolean[] in_itemtag = new boolean[numberOfItems];
Car newCar = new Car();
private ArrayList<Car> list = new ArrayList<Car>();
// ===========================================================
// Getter & Setter
// ===========================================================
public ArrayList<Car> getParsedData() {
return this.list;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.list = new ArrayList<Car>();
}
#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("outertag")) {
this.in_outertag = true;
}else if (localName.equals("cartag")) {
this.in_cartag = true;
newCar.setType(atts.getValue("type")); //setType(...) is the setter defined in car class
}else if (localName.equals("itemtag")) {
if((atts.getValue("name")).equals("model")){
this.in_itemtag[0] = true;
}else if((atts.getValue("name")).equals("color")){
this.in_itemtag[1] = true;
}else if((atts.getValue("name")).equals("year")){
this.in_itemtag[2] = true;
}
}
}
/** 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("cartag")) {
this.in_cartag = false;
Car carTemp = new Car();
carTemp.copy(newCar, carTemp); //this method is defined on car class, and is used to copy the
//properties of the car to another Object car to be added to the list
list.add(carTemp);
}else if (localName.equals("itemtag")){
if(in_itemtag[0]){
this.in_itemtag[0] = false;
}else if(in_itemtag[1]){
this.in_itemtag[1] = false;
}else if(in_itemtag[2]){
this.in_itemtag[2] = false;
}
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(in_itemtag[0]){
newCar.setModel(new String(ch, start, length));
}else if(in_itemtag[1]){
newCar.setColor(new String(ch, start, length));
}else if(in_itemtag[2]){
newCar.setYear(new String(ch, start, length));
}
}
}
After this, you can get the parsed data in the Activity using:
...
ArrayList<Car> ParsedData = myExampleHandler.getParsedData();
...
I hope this helps someone.
Attention: I don't have tested exactly like this, but is almost the same of my solution so it should work...
And sorry for my bad English...
I parsing the xml using sax parser in android. My xml structure is as given below
<customerlist>
<Customer>
<customerId>2</customerId>
<customerFname>prabhu</customerFname>
<customerLname>kumar</customerLname>
<customerImage>
iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABHNCSVQICAgIfAhkiAAACJ9JREFUaIHtmllsXFcZx3/n3Due8XgcO3a8xG72tGkTknRJG7qAaEtbhFjVJUpBoBahgkoRUCFe+lCJvkAKCGgFPJQK0VKWqIhShMhL0mahLU1ImjZp0ziZLN5dezxje5Z7z/l4uDOOl9mcOskLf+vTle79fM63nPM/53xn4P+4tFDzrDffkEoKpQxTgAZcoCYvzpT3FxKWwHAD5PLiT3k/DW6JRjQQAupuuadx/VWbYk9b5dcg+uJkQlnR4uaOvjn28J7ticPAOOARODVdtUQTYaDu+7/86GONLfqbvvUiF9DcknB1KJMYtL/a9shrTxA4kWNGFkploAaoa1+t7mxfWhcRqTgULwiUUpG+02N3Aj8jyEBupk4xBxRBBmLJ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Cd/JNlDp/nhCBCgkoz0KFCVye/2Eo/T5KhYLmxOFg3++5uu1BLFJkFZ6DWCoWB0s5MOl3ZQcMa1u25HsEJYoTwzs4PrKDluhVGJMtzZXVyjmbqt4LCQTF1cIZtbTAkoabWNl0B6IEFLhOLceH/8nGtq+indC5s9QcRcFU8prTXsgAmQMHDox0dXUlfd/XgBKRElyoEFnO290vTWtirPllrGyma3gHag40KiBoRCtsZlxGgAxFrliDnou/a8rLJmA50AhECO6qLgY8AqMTQBx4ExgGkvlv04wthhhQB7QCC4B6gpvL2bcQFwYGyAIpAqMHCO6Jx6nynrgQgWGCq80kgfEX+mcGBVgCJwpXqxlmRL6AUhnQBAa7U54X43cSBRROYD6BI4XnLFL9H0iaJNCEw0eHAAAAAElFTkSuQmCC
</customerImage>
</Customer>
</customerlist>
I am able to get customerId, customerFname, customrLname, but for customerImage I am not getting complete string I am only getting part of the string i.e (iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABHNCSVQICAgIfAhkiAAACJ9JREFUaIHtmllsXFcZx3/n3Due8XgcO3a8xG72tGkTknRJG7qAaEtbhFjVJUpBoBahgkoRUCFe+lCJvkAKCGgFPJQK0VKWqIhShMhL0mahLU1ImjZp0ziZLN5dezxje5Z7z/l4uDOOl9mcOskLf+vTle79fM63nPM/53xn4P+4tFDzrDffkEoKpQxTgAZcoCYvzpT3FxKWwHAD5PLiT3k/DW6JRjQQAupuuadx/VWbYk9b5dcg+uJkQlnR4uaOvjn28J7ticPAOOARODVdtUQTYaDu+7/86GONLfqbvvUiF9DcknB1KJMYtL/a9shrTxA4kWNGFkploAaoa1+t7mxfWhcRqTgULwiUUpG+02N3Aj8jyEBupk4xBxRBBmLJVEqiEznEWgBEBI8MYVVbdHYpFEZ8tNIUT65CrAEFSjmAxZcsIRUp3p7WJFNZAWJAOi/+VJ1SE9IBQmKsgwGsAgth3cCVTZ9FRIFViBXESjC9rCKTG+MjLfcRdRZjJ7+d0/P8LEsab6YxshxjfMK6gU9f/hS+tfk+ZogBMdYhmI8FEpmGcpO4xs8pba1grQCWzcsfYVH0ckbHexkcP8K1nV+jNbaWfad+zliml8+seYpoaCEnh3ZzZfMXuKzhBg50P8v69nuJ1SzmpSPfwPiGnJ+jM7aZtW1fpCW6FusJ6Nk50Br8nNIEQ7posEtlQEGet0QQEayxdMQ2se/U06xsvh3P5NjQvpUzI6+zsul2Wus3MjT+PuO5IXybZVnjzYxMxLFiibhNdCf307HgBqI1bcTcdm5c+m26R/fjKBfBTvYzU+wMm+bkQDaXYiKTJJ1JIlaTM0lWNt7GFc2fIuZ2MJB6l8M9L+JZD7GKkx/sYTDVRSY7Qcab4N8nf01qYpDB1HFOD7+OlhqyuVE8P4OIomvwFTw/O9nHTJnIJMnmUlNtqnoIAbChfQurlrVj
)
My xmlHandler code is below
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import com.bvbi.invoicing.client.android.customer.model.CustomerPojoInList;
public class CustomerListParser extends DefaultHandler {
Boolean currentElement = false;
String tempValue = null;
CustomerPojoInList customer = null;
public static ArrayList<CustomerPojoInList> customers = null;
#Override
public void startDocument() throws SAXException {
customers = new ArrayList<CustomerPojoInList>();
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("Customer"))
{
/** Start */
customer = new CustomerPojoInList();
}
}
/** Called when tag closing */
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
String currentValue = tempValue;
tempValue = "";
/** set value */
if (localName.equalsIgnoreCase("customerId"))
customer.setCustomerId(currentValue.toString());
else if (localName.equalsIgnoreCase("customerFname"))
customer.setCustomerFname(currentValue.toString());
else if (localName.equalsIgnoreCase("customerLname"))
customer.setCustomerLname(currentValue.toString());
else if (localName.equalsIgnoreCase("customerImage"))
{
Log.d("prabhu","Customer image in parser......"+currentValue);
customer.setCustomerImage(currentValue.toString());
}
else if (localName.equalsIgnoreCase("Customer"))
customers.add(customer);
}
/** Called to get tag characters */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
tempValue = new String(ch,start, length);
if(tempValue.equals(null))
tempValue = "";
currentElement = false;
}
}
#Override
public void endDocument() throws SAXException {
}
}
Please help me to fix the issue.
In sax parser, characters() method parses only maximum of 1024 characters each time. So we need to append the strings until all the characters are parsed.
I changed the above code as follows
public void characters(char[] ch, int start, int length)
throws SAXException
{
Log.d("prabhu","Customer image length in parser......"+length);
if (currentElement ) {
tempValue = new String(ch,start, length);
if(tempValue.equals(null))
tempValue = "";
}
tempValue = tempValue+new String(ch,start, length);
}
The output you posted is exactly 1024 characters. This looks like a certain buffer size. How do you get this output? Maybe check that method and / or your CustomerPojoInList.
I very much believe, that there is some buffer involved that has a maximum of 1024 characters...
Good luck!
first time post. Updated answer with something that might help others. I hope it is not too specific to my particular problem. I am parsing an RSS feed that I create myself with a really long description but the other tags you are interested in, i.e. feed title, date and URL are always short. The description contains information about social events. Within the description, I use tags that I later parse to give me information about the event such as event date (different from RSS pubDate), (Location), (ticketDetails), (Phone), etc, you get the idea.
A good way to handle this is with a slight modification of the answer in this post. I added tags to the description for (Event) and (EndEvent) and I keep appending to my String Builder until I get "(EndEvent)". That way i know i have the full string. It might not work for your situation if you dont control the feed unless you know there is always a certain string at the end of your RSS description.
Posting in case this (cough, hack) helps anyone. Code is as follows:
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
strBuilder = new StringBuilder();
if ("item".equals(qName)) {
currentItem = new RssItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
} else if ("link".equals(qName)) {
parsingLink = true;
}
else if ("pubDate".equals(qName)) {
parsingDate = true;
}
else if ("description".equals(qName)) {
strBuilder = new StringBuilder(); //reset the strBuilder variable to null
parsingDescription = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
String descriptionTester = strBuilder.toString();
if ("item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
} else if ("link".equals(qName)) {
parsingLink = false;
}
else if ("pubDate".equals(qName)) {
parsingDate = false;
}
//else
// currentItem.setDescription(descriptionTester);
else if ("description".equals(qName) && descriptionTester.contains("(EndEvent)")) {
parsingDescription = false;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (strBuilder != null) {
for (int i=start; i<start+length; i++) {
strBuilder.append(ch[i]);
}
}
if (parsingTitle) {
if (currentItem != null)
currentItem.setTitle(new String(ch, start, length));
parsingTitle = false;
}
else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
else if (parsingDate) {
if (currentItem != null) {
currentItem.setDate(new String(ch, start, length));
parsingDate = false;
}
}
else if (parsingDescription) {
if (currentItem != null && strBuilder.toString().contains("(EndEvent)" )) {
String descriptionTester = strBuilder.toString();
currentItem.setDescription(descriptionTester);
parsingDescription = false;
}
}
}
As I said, hope that helps someone as I was stumped on this for a while!
I am making an small application in android of webservices through Sax parser my link is
(http://www.anddev.org/images/tut/basic/parsingxml/example.xml)I am able to display the value of ****<**innertag>,******But can't able to display the value of in theTextView
Here is my sorcs code
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
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 namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = true;
}else if (localName.equals("innertag")) {
//this.in_innertag = true;
String attrValue = atts.getValue("sampleattribute");
myParsedExampleDataSet.setExtractedString(attrValue);
}else if (localName.equals("mytag")) {
//this.in_mytag = true;
String attrValue = atts.getValue("mytag");
myParsedExampleDataSet.setExtractedString1(attrValue);
}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.setExtractedString1(new String(ch, start, length));
}
}
}![enter image description here][1]
You have this.in_mytag = true commented out in startElement(). Therefore the code block in the characters() function that sets ExtractedString1 isn't executing because in_mytag is false.
One other thing when handling the start of mytag: String attrValue = atts.getValue("mytag"); is unnecessary. It should be handled in the characters() function (I suspect you simply had it for debugging purposes).
I'm designing an App for android and I need to parse an XML file, I've been told SAX parsers are better for mobile devices to I've been trying to use it but I've gotten stuck. Here is the XML code:
<current_conditions>
<condition data="Clear"/>
<temp_f data="50"/>
<temp_c data="10"/>
<humidity data="Humidity: 76%"/>
<icon data="/ig/images/weather/sunny.gif"/>
<wind_condition data="Wind: NE at 14 mph"/>
</current_conditions>
<forecast_conditions>
<day_of_week data="Tue"/> ****
<low data="43"/>
<high data="64"/> ****
<icon data="/ig/images/weather/mostly_sunny.gif"/>
<condition data="Mostly Sunny"/>
</forecast_conditions>
<forecast_conditions>
<day_of_week data="Wed"/>
<low data="43"/>
<high data="64"/>
<icon data="/ig/images/weather/sunny.gif"/>
<condition data="Clear"/>
</forecast_conditions>
I am trying to get values of only the two tags with * by the side but it returns the values at the end of the document instead. How do I solve this problem as I only want certain values in the XML. Here is my code:
public class ExampleHandler extends DefaultHandler {
private boolean in_in_current_conditions = false;
private boolean in_in_forecast_conditions = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
}
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException
{
if (localName.equals("forecast_information"))
{
this.in_forecast_information = true;
}
else if (localName.equals("current_conditions"))
{
this.in_in_current_conditions = true;
}
else if (localName.equals("forecast_conditions"))
{
this.in_in_forecast_conditions = true;
}
else if (localName.equals("high")) {
if (this.in_in_forecast_conditions)
{
String attrValue = atts.getValue("data");
myParsedExampleDataSet.setCurrtempValue(attrValue);
}
} else if (localName.equals("day_of_week")) {
if (this.in_in_forecast_conditions) {
String attrValue1 = atts.getValue("data");
myParsedExampleDataSet.setLowValue(attrValue1);
}
}
}
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("forecast_information")) {
this.in_forecast_information = false;
} else if (localName.equals("current_conditions")) {
this.in_in_current_conditions = false;
} else if (localName.equals("forecast_conditions")) {
this.in_in_forecast_conditions = false;
}
}
#Override
public void characters(char ch[], int start, int length) {
}
}
If I were you then I would just use the Simple XML framework to do the XML parsing work for you. It would not be too difficult then to just create a few objects that could tease this data out of the XML.
P.S. I use the Simple project for all my XML so I even wrote a blog post explaining how to use it in Android projects: you can read it here.
To get those two values you would do something like this:
public class ExampleHandler extends DefaultHandler {
private static final String FORECAST_CONDITION = "forecast_condition";
private boolean day_of_week_dataWanted = false;
private boolean high_dataWanted = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
public ExampleHandler() {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if(FORECAST_CONDITION.equals(localName)){
if("day_of_week".equals(localName)){
day_of_week_dataWanted = true;
}
if("high".equals(localName)){
high_dataWanted = true;
}
}
}
#Override
public void characters(char ch[], int start, int length) {
if(day_of_week_dataWanted){
myParsedExampleDataSet.setLowValue(new String(ch, start, length));
day_of_week_dataWanted = false;
}
if(high_dataWanted){
myParsedExampleDataSet.setCurrtempValue(new String(ch, start, length));
high_dataWanted = false;
}
}
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
}
}
But there are more graceful solutions you could look at, hopefully this gives you a hint.
I've sorted this by using populating the values in Arrays and when I want to display them I simple use their position in the array to call them