SAXParser Android, ArrayList repeating elements - java

I am currently just trying to process the elements within the item nodes. I am just focusing on the title at this point for simplicity, but I am finding that when it parses, I am just getting the same element three times.
http://open.live.bbc.co.uk/weather/feeds/en/2643123/3dayforecast.rss
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
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 XMLHelper extends DefaultHandler {
private String URL_Main="http://open.live.bbc.co.uk/weather/feeds/en/2643123/3dayforecast.rss";
String TAG = "XMLHelper";
Boolean currTag = false;
String currTagVal = "";
public ItemData item = null;
public ArrayList<ItemData> items = new ArrayList<ItemData>();
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(URL_Main).openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
// Receives notification of the start of an element
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i(TAG, "TAG: " + localName);
currTag = true;
currTagVal = "";
if (localName.equals("channel")) {
item = new ItemData();
}
}
// Receives notification of end of element
public void endElement(String uri, String localName, String qName)
throws SAXException {
currTag = false;
if (localName.equalsIgnoreCase("title"))
item.setTitle(currTagVal);
else if (localName.equalsIgnoreCase("item"))
items.add(item);
}
// Receives notification of character data inside an element
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
}

The reason you are getting the same value thrice is because you are creating the object when there is a channel tag in startElement method.
if (localName.equals("channel")) {
item = new ItemData();
}
I guess you should initiate the object whenever there is a item tag as below
if (localName.equals("item")) { // check for item tag
item = new ItemData();
}

Remodify your whole project, you need 3 classes :
1.ItemList
2.XMLHandler extends Default handler
3.SAXParsing activity
Make your code organized first
In your XMLHandler class extend default handler your code should look like
public class MyXMLHandler extends DefaultHandler
{
public static ItemList itemList;
public boolean current = false;
public String currentValue = null;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
current = true;
if (localName.equals("channel"))
{
/** Start */
itemList = new ItemList();
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
current = false;
if(localName.equals("item"))
{
itemList.setItem(currentValue);
}
else if(localName.equals("title"))
{
itemList.setManufacturer(currentValue);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if(current)
{
currentValue = new String(ch, start, length);
current=false;
}
}
}
ItemList class is used to set , setter and getter methods to pass in values of arraylist and retrieve those array lists in the SAXParsing activity.
I hope this solution helps. :D

Related

Not having a response when I call my web service GET request

I'm a student who needs help with a homework problem. The thing is that I wrote a rest web service using SAX parser in order to display a xml file that I have stored on the same folder of the project. The problem is that when I use the path I provided to it, it's not happening anything. I'm probably doing something wrong on my code. Here it is:
package com.crunchify.restjersey;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
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;
#Path("/saxbooksxml")
public class SaxBooksXml {
public SaxBooksXml(){}
#GET
#Produces(MediaType.APPLICATION_XML)
public void gofindsaxbooks(){
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = null;
try {
saxParser = factory.newSAXParser();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DefaultHandler handler = new DefaultHandler(){
boolean bauthor = false;
boolean btitle = false;
boolean bgenre = false;
boolean bprice = false;
boolean bpublish_date = false;
boolean bdescription = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{
if(qName.equalsIgnoreCase("author")){
bauthor = true;
}
if(qName.equalsIgnoreCase("title")){
btitle = true;
}
if(qName.equalsIgnoreCase("genre")){
bgenre = true;
}
if(qName.equalsIgnoreCase("price")){
bprice = true;
}
if(qName.equalsIgnoreCase("publish_date")){
bpublish_date = true;
}
if(qName.equalsIgnoreCase("description")){
bdescription = true;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException{
}
public void characters(char ch[], int start, int lenght) throws SAXException{
if(bauthor){
System.out.println("author: "+new String(ch, start, lenght));
bauthor = false;
}
if(btitle){
System.out.println("title: "+new String(ch, start, lenght));
btitle = false;
}
if(bgenre){
System.out.println("genre: "+new String(ch, start, lenght));
bgenre = false;
}
if(bprice){
System.out.println("price: "+new String(ch, start, lenght));
bprice = false;
}
if(bpublish_date){
System.out.println("publish_date: "+new String(ch, start, lenght));
bpublish_date = false;
}
if(bdescription){
System.out.println("description: "+new String(ch, start, lenght)+"\n");
bdescription = false;
}
}
};
try {
saxParser.parse("Books.xml", handler);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is a print of part of the file I'm trying to parse. The idea is to display it on the browser exactly the same.
enter image description here
Your method gofindsaxbooks returns void
Change it like below:
#GET
#Produces(MediaType.APPLICATION_XML)
public Response gofindsaxbooks()
{
return Response.status(200).entity("Test XML created").build();
}

SAX startElement is never called

I'm trying to use SAX to parse an XML but it happens that the Handler's startElement() is never called. I do not have any clues why it doesnt work.
This is my code
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class ChangePasswordXMLParser {
public static void parseXML(InputStream xml) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
ChangePasswordHandler handler = new ChangePasswordHandler();
saxParser.parse(xml, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
private static class ChangePasswordHandler extends DefaultHandler {
boolean bfReturn;
public ChangePasswordHandler() {
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("return")) {
bfReturn = true;
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bfReturn) {
AuthenticateUserResult user = SessionManager.getInstance().getUser();
String value = new String(ch, start, length);
EventBus.getDefault().post(new AlterarSenhaEvent(value));
bfReturn = false;
}
}
}
}
and this is and XML Input example:
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body SOAP-ENC:encodingStyle="http://schemas.xmlsoap.org/soap/envelope/">
<NS1:ChangePasswordResponse xmlns:NS1="urn:exemple">
<return xsi:type="xsd:string">03351-0</return>
</NS1:ChangePasswordResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I did see in other topic here in stackoverflow that may be the imports, but my imports seems fine to me.
Any ideas? Thanks!
You set AlterarSenhaHandler instead of PasswordHandler.
So PasswordHandler is never called.
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("return")) {
System.out.println("inside return");
}
}
proofs that your code is valid

How to access a xml file from a .jar for execute jar from shell_exec php function

jar from a apache server with php.
I use shell_exec and a give her my jar file.
But because i parse an xml file on my java class i have problem. Jar can't access xml.
Files
SampleSax.java
package phpJavaPack;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class SampleSAX {
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
/*int i=0;
MyBufferedReaderWriter f = new MyBufferedReaderWriter();
f.openRFile("dblp.xml");
String sLine="";
while ((i<10) && (sLine=f.readLine()) != null) {
System.out.println(sLine);
i++;
}*/
int i=0;
while(i<args.length){
System.out.println("Argument's: " + args[0]);
System.setProperty("entityExpansionLimit", "1000000");
SAXParserFactory spfac = SAXParserFactory.newInstance();
spfac.setNamespaceAware(true);
SAXParser saxparser = spfac.newSAXParser();
MyHandler handler = new MyHandler(args[i]);
InputSource is = new InputSource("dblpmini.xml");
is.setEncoding("ISO-8859-1");
System.out.println("Please wait...");
saxparser.parse(is, handler);
System.out.println("---->" + handler.getprofessorsPublications());
i++;
}
//System.out.println("#####################################################################################################");
//System.out.println("List of George A. Vouros: " + handler.getprofessorsPublicationsValue("George A. Vouros"));
//System.out.println(handler.getProfessors());
//handler.createHtmlPage();//emfanizei mia html selida me ta apotelesmata
}
}
MyHandler.java
package phpJavaPack;
import java.util.ArrayList;
import java.util.Hashtable;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandler extends DefaultHandler {
private Publication publication;
protected Hashtable<String, ArrayList<Publication>> professorsPublications = new Hashtable<String, ArrayList<Publication>>();
private String temp ;
private ArrayList<Publication> al;
//private EntryLd entry = new EntryLd();
// public MyHandler() {
// super();
//
// String[] namesTable = entry.getNamesInput();
//
//
// for (String name: namesTable) {
//
// al = new ArrayList<Publication>();
// professorsPublications.put(name, al);
// }
//
// System.out.println("HashTable: " + professorsPublications);
// }
public MyHandler(String authorForSearch){
super();
String name = authorForSearch;
al = new ArrayList<Publication>();
professorsPublications.put(name, al);
System.out.println("HashTable: " + professorsPublications);
}
public Hashtable<String, ArrayList<Publication>> getprofessorsPublications() {
return professorsPublications;
}
public ArrayList<Publication> getprofessorsPublicationsValue(String author) {
return professorsPublications.get(author);
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
temp = "";
if (qName.equalsIgnoreCase("article") || qName.equalsIgnoreCase("inproceedings")
|| qName.equalsIgnoreCase("proceedings") || qName.equalsIgnoreCase("book")
|| qName.equalsIgnoreCase("incollection") || qName.equalsIgnoreCase("phdthesis")
|| qName.equalsIgnoreCase("mastersthesis") || qName.equalsIgnoreCase("www")) {
publication = new Publication();
}
}
public void characters(char[] ch, int start, int length) {
temp = new String(ch, start, length);
System.out.println("----->>>" + temp);
//System.out.print(" <--- My temp's start: " + temp + " :My temp's end --> ");
}
public void endElement(String uri, String localName, String qName) throws SAXException
{
if (qName.equalsIgnoreCase("article") || qName.equalsIgnoreCase("inproceedings")
|| qName.equalsIgnoreCase("proceedings") || qName.equalsIgnoreCase("book")
|| qName.equalsIgnoreCase("incollection") || qName.equalsIgnoreCase("phdthesis")
|| qName.equalsIgnoreCase("mastersthesis") || qName.equalsIgnoreCase("www"))
{
for(int i=0; i<publication.getAuthors().size(); i++) {
String authorName = publication.getAuthors().get(i);
if(this.professorsPublications.containsKey(authorName)) {
this.publication.setType(localName);
this.professorsPublications.get(authorName).add(publication);
}
}
}
if(qName.equalsIgnoreCase("author")) {
publication.addAuthor(temp);
}
else if(qName.equalsIgnoreCase("title")) {
publication.setTitle(temp);
}
else if(qName.equalsIgnoreCase("year")) {
publication.setYear(Short.parseShort(temp));
}
else if(qName.equalsIgnoreCase("booktitle")) {
publication.setBooktitle(temp);
}
//String xl = publication.toString();
//System.out.println(xl);
}
}
How can give right the xml on a runnable jar?
Thnx
see PHP exec() command: how to specify working directory? - most probably the proc_open suggestion/example there is the best one
see the other suggestions at that thread too, like chdir

Why is my variable is null?

I do this
package file;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.LocatorImpl;
import org.xml.sax.helpers.XMLReaderFactory;
public class GetNatureSax implements ContentHandler {
private final static Logger _logger = Logger.getLogger(GetNatureSax.class.getName());
private boolean isCurrentElement = false;
private Locator locator;
private String _parameterValue = null;
public GetNatureSax() {
super();
locator = new LocatorImpl();
}
public String getValeurParametre() {
return _parameterValue;
}
public void setDocumentLocator(Locator value) {
locator = value;
}
public void startDocument() throws SAXException {}
public void endDocument() throws SAXException {}
public void startPrefixMapping(String prefix, String URI) throws SAXException {
}
public void endPrefixMapping(String prefix) throws SAXException {}
public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attributs)
throws SAXException {
if (localName.equals("Nature")) {
isCurrentElement = true;
}
}
public void endElement(String nameSpaceURI, String localName, String rawName) throws SAXException {
if (localName.equals("Nature")) {
isCurrentElement = false;
}
}
public void characters(char[] ch, int start, int end) throws SAXException {
if (isCurrentElement) {
_parameterValue = new String(ch, start, end);
}
}
public void ignorableWhitespace(char[] ch, int start, int end) throws SAXException {
System.out.println("espaces inutiles rencontres : ..." + new String(ch, start, end) + "...");
}
public void processingInstruction(String target, String data) throws SAXException {
System.out.println("Instruction de fonctionnement : " + target);
System.out.println(" dont les arguments sont : " + data);
}
public void skippedEntity(String arg0) throws SAXException {}
public void parseFichier(String i_fichierATraiter) {
XMLReader saxReader;
try {
saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
saxReader.setContentHandler(new GetNatureSax());
saxReader.parse(i_fichierATraiter);
System.out.println(_parameterValue);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My XML:
...
<Reference>
<Nature>ACHAT</Nature>
<Statut>2</Statut>
<Type-Gest>RE</Type-Gest>
<Gest>RE_ELECTRA</Gest>
<Type-Res>D</Type-Res>
<Nb-h>24</Nb-h>
</Reference>
...
why when it execute this line
System.out.println(_parameterValue);
my variable is null and before when i debug my variable is not null
Because you instantiate a new GetNatureSax and give it to the SaxReader has a Content Handler.
So when the parsing has ended, it is the new GetNatureSax instance that have been modified and which have the field _parameterValue set, not the current instance (this).
Just modify your parseFichier method like this:
saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
saxReader.setContentHandler(this); // here
saxReader.parse(i_fichierATraiter);
System.out.println("Found: " + getValeurParametre());
Using my debugger I can see you are using two GetNatureSax
saxReader.setContentHandler(new GetNatureSax());
This creates a second GetNatureSax object where is where the value is being set.
Changing it to
saxReader.setContentHandler(this);
fixed the problem.

Java Sax XML Parser, parsing custom "values" within XML tags?

I haven't worked much with XML before so maybe my ignorance on proper terminology is hurting me in my searches on how to do this. I have the code snippet below which I am using to parse an XML file like the one below. The problem is that it only picks up XML values within <Tag>Value</Tag> but not for the one below where I need to get the value of TagValue, which in this case would be "Russell Diamond".
I would appreciate if anyone can offer assistance as to how to get custom values like this. Thanks.
<Tag TagName="#Subject" TagDataType="Text" TagValue="Russell Diamond"/>
The snippet I am using:
public void printElementNames(String fileName) throws IOException {
//test write to file
FileWriter fstream = new FileWriter("/home/user/Desktop/readEDRMtest.txt");
final BufferedWriter out = new BufferedWriter(fstream);
//
try {
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
System.out.println("XML Elements: ");
DefaultHandler handler = new DefaultHandler() {
public void startElement(String uri, String lName, String ele,
Attributes attributes) throws SAXException {
// print elements of xml
System.out.println(ele);
try {
out.write(ele);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
System.out.println("Value : "
+ new String(ch, start, length));
try {
out.write("Value : "
+ new String(ch, start, length));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
You want to look into extracting attributes. Search on that and you'll find your answer.
The DefaultHandler class's startElement(...) method passes a parameter called attributes that refers to an Attribute object. The API for the Attribute interface will describe how to extract the information you need from this object.
For example:
out.write(attributes.getValue("TagValue"));
This is a stripped down and working version of your code snippet:
import java.io.File;
import java.io.IOException;
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 SAX
{
public static void main(String[] args) throws IOException {
new SAX().printElementNames("Delete.xml");
}
public void printElementNames(String fileName) throws IOException
{
try {
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
DefaultHandler handler = new DefaultHandler()
{
public void startElement(String uri, String lName, String ele, Attributes attributes) throws SAXException {
System.out.println(ele);
System.out.println(attributes.getValue("TagValue"));
}
public void characters(char ch[], int start, int length) throws SAXException {
System.out.println("Value : " + new String(ch, start, length));
}
};
parser.parse(new File(fileName), handler);
}catch(Exception e){
e.printStackTrace();
}
}
}
Content of Delete.xml
<Tag TagName="#Subject" TagDataType="Text" TagValue="Russell Diamond"/>
Further reading:
http://www.java-samples.com/showtutorial.php?tutorialid=152

Categories

Resources