XMLParsing problem - iphone

I display List of date's on my table view....
based on the date's.. i need to search location. and title
"with the help of url".
example
String *url=#"http://compliantbox.com/party_temperature/djsearch.php?date=?"
for the selected date.
i appended the date value to the string url.
So i need to parse again same xml parser. with date search.
<root>
<event title="event_title"location="new york"date="12/01/2011"/>
<event title="event_title2"location="california"date="13/01/2011"/>
<event title="event_title3"location="new york"date="14/01/2011"/>
</root>
here my array get's Re-Initialization.
so i get conflict. when displaying data....
I need to not re-Initialization my array again. and again...
I need to initialize my array only once in entire application.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:#"root"]){
dateListArray=[[NSMutableArray alloc] init];
}
}
I Hope you people understand my problem.
Please help me out .
#Thanks to All.

One way that you should trying here,
if([dateListArray count] > 0)
{
[dateListArray removeAllObjects];
[dateListArray release];
}
dateListArray=[[NSMutableArray alloc] init];
And other way you should also be trying,
dateListArray=[[NSMutableArray alloc] init];
above statement write down in -(void)viewDidLoad event and
if([dateListArray count] > 0)
{
[dateListArray removeAllObjects];
}
above write down in your required function.

I guess:
NSMutableArray:-removeAllObjects
may help~

Related

How to use NSXMLParser to Find 1 Element

I have searched the internet for several days, but I cannot find a consise answer. I want to make a simple practice weather app that shows the temperature for a hardcoded zip code.
Here is the XML
<data>
<request>
<type>Zipcode</type>
<query>08003</query>
</request>
<current_condition>
<observation_time>08:29 PM</observation_time>
<temp_C>11</temp_C>
<temp_F>52</temp_F>
<weatherCode>143</weatherCode>
<weatherIconUrl>
<![CDATA[
http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0006_mist.png
]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[ Mist ]]>
</weatherDesc>
<windspeedMiles>4</windspeedMiles>
<windspeedKmph>7</windspeedKmph>
<winddirDegree>210</winddirDegree>
<winddir16Point>SSW</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>87</humidity>
<visibility>5</visibility>
<pressure>1013</pressure>
<cloudcover>100</cloudcover>
</current_condition>
<weather>
<date>2012-12-08</date>
<tempMaxC>13</tempMaxC>
<tempMaxF>55</tempMaxF>
<tempMinC>9</tempMinC>
<tempMinF>48</tempMinF>
<windspeedMiles>6</windspeedMiles>
<windspeedKmph>9</windspeedKmph>
<winddirection>W</winddirection>
<winddir16Point>W</winddir16Point>
<winddirDegree>260</winddirDegree>
<weatherCode>122</weatherCode>
<weatherIconUrl>
<![CDATA[
http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png
]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[ Overcast ]]>
</weatherDesc>
<precipMM>3.1</precipMM>
</weather>
</data>
ALL I want to do is to extract the *temp_F* and store it in a NSString.
If all you want is a single value for a single element that only appears once in the XML then I would do some simple string search instead of bothering with a full blown XML parser.
Get the range of the substring #"<temp_F>" and the substring #"</temp_F>" and grab the value in between.
Since you already mentioned using NSXMLParser, just go with that. Set your delegate to implement the protocol
#interface MyClass : NSObject <NSXMLParserDelegate>
Watch for the opening tag of your xml entry (looks to be in this case) with something like
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
if ( [elementName isEqualToString:#"temp_F"] ) {
// Set flag and reset string
self.foundTargetElement = true;
if ( self.myMutableString ) {
self.myMutableString = nil;
self.myMutableString = [[NSMutableString alloc] init];
}
}
}
Next implement
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ( self.foundTargetElement ) {
[self.myMutableString appendString:string];
}
}
and using the same pattern as above, watch for your tag, () and append its value to your string, or do whatever else you want with the data:
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
self.foundTargetElement = false;
// Do something with your result, or
// Wait until entire document has been parsed.
}
Let me know if that works out for you.

How can I parse XML of having multiple Nodes with same name and show in different controller?

See the XML below
http://sosmoths.com/.xml/moths.xml
This XML having multiple images name, I have to show the different title(There are four title) in their respective Controller.
I have 4 controller, and have to show each moth value in different Controller, along with their multiple images values, how can I do it?
I can make single object of should I make four objects?
I am a bit confused in it, please help me.
This XML having multiple images name, I have to show the different
title(There are four title) in their respective Controller. I have 4
controller, and have to show each moth value in different Controller,
along with their multiple images values, how can I do it?
This sounds less like an XML parsing problem and more like an app architecture problem.
That XML basically describes some data and said data would typically be represented by objects in your application. You could go with a CoreData based solution whereby you parse the XML into a local CoreData store (in memory or on disk, matters not) and then display the managed objects as per usual.
Or, assuming that is representative of a typical set of data, you could parse it into your own hand rolled objects (or, even, dictionaries and arrays), then display from there.
There are dozens of questions about parsing XML on SO (and via Google).
The second part of your question hasn't been addressed. Basically, you need to properly layer your app into the model-view-controller pattern. Your model layer would parse the XML and create an object graph that represents the data. Each controller would have a reference to that single model.
This will work fine as long as your app is read only. If the various controllers are expected to also edit the object graph, then it'll need to be a bit more complex in that you'll have to deal with change propagation (this is where CoreData shines; it makes change management, propagation, validation, and undo relatively straightforward).
With TBXML you can easily parse the xml and it will convert it into objects to use:
http://www.tbxml.co.uk/TBXML/TBXML_Free.html
and libxml2 is also that you can use easily to parse.
try this it worked properly
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
NSLog(#"%#",elementName);
if([elementName isEqualToString:#"moths"]){
mytblarray=[[NSMutableArray alloc] init];
} else if([elementName isEqualToString:#"moth"]){
tmpdic=[[NSMutableDictionary alloc] init];
}
else if([elementName isEqualToString:#"images"]){
imgArray=[[NSMutableArray alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(tmpstr!=nil && [tmpstr retainCount]>0){ [tmpstr release]; tmpstr=nil; }
tmpstr=[[NSString alloc] initWithString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"moth"]){
[mytblarray addObject:tmpdic];
[tmpdic release];
}if([elementName isEqualToString:#"images"]){
[tmpdic setValue:imgArray forKey:elementName];
}
else if([elementName isEqualToString:#"image"]){
[imgArray addObject:tmpstr];
}
else if([elementName isEqualToString:#"id"] || [elementName isEqualToString:#"title"]||[elementName isEqualToString:#"description"]){
[tmpdic setValue:tmpstr forKey:elementName];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(#"%#",[imgArray description]);
NSLog(#"%#",[mytblarray description]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//get value like it
NSString *cellValue = [[mytblarray objectAtIndex:indexPath.row] valueForKey:#"id"];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//get value like it
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithDictionary:
[mytblarray objectAtIndex:indexPath.row]];
}

NSXMLParser Parsing RSS into a Custom Object

I have my nsxmlparser parsing the news feed just fine:
http://www.skysports.com/rss/0,20514,12433,00.xml
However when it comes to saving it into my custom object, although I recieve output of each entry in the xml, it only stores one record which happens to be the last one.
Please see my code:
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"rss"]) {
currentNews = [[NewsParse alloc] init];
}
}
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"description"]) {
currentNews.newsTitle = currentNodeContent;
NSLog(#"description = %#",currentNodeContent);
}
if([elementName isEqualToString:#"rss"])
{
[news addObject:currentNews];
[currentNews release];
currentNews = nil;
[currentNodeContent release];
currentNodeContent = nil;
}
}
This method worked fine with a twitter feed but now i'm assuming because the xml is formed differently I cannot get it to work.
I'm still pretty new to using NSXMLParser so any help would be cool :)
Looking at the RSS feed it appears that you are looking for the wrong tag to begin and end your objects. You need to replace
[elementName isEqualToString:#"rss"]
with
[elementName isEqualToString:#"item"]
in both places.
The way you are doing it now you are looking at the entire page as 1 object. You need to look at each "item" ( <item> </item> ) as an object. The reason why you are successfully getting the last object to save is because you replacing each "description" every time you run through your items. It is replacing the string over and over and over again before you actually save. The last object never gets replaced before saving and therefor the only object you see as saved..
Hmmm, currentNews.newsTitle is changed every time and once it reads the closing rss tag, it has the value of the last feed. What type of object is your currentNews? If you want to keep all different titles, then you have to add them to some sort of object that holds several values, like an array, when you find the closing tag of description simply copy the string for currentNodeContent into an individual instance of news.
I would actually allocate the instance of currentNews in the didEndElement tag outside any comparisson just in case you have more elements to look for. That closing tag probably like this:
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"title"]) {
self.currentNews.newsTitle = [[NSString alloc] initWithString:currentNodeContent];
}
if ([elementName isEqualToString:#"description"]) {
self.currentNews.newsDescription = [[NSString alloc] initWithString:currentNodeContent];
}
if ([elementName isEqqualToString:#"link"]) {
self.currentNews.newsLink = [[NSString alloc] initWithString:currentNodeContent];
}
if ([elementName isEqualToString:#"guid"]) {
self.currentNews.newsGuid = [[NSString alloc] initWithString:currentNodeContent];
}
if ([elementName isEqualToString:#"pubDate"]) {
self.currentNews.newsPubDate = "probably a date formatter here";
}
if ([elementName isEqualToString:#"cathegory"]) {
self.currentNews.newsCathegory = [[NSString alloc] initWithString:currentNodeContent];
}
blah...
blah...
if ([elementName isEqualToString:#"item"]) {
[news addObject:currentNews];
[self.currentNews.newsTitle release];
[self.currentNews.newsDescription release];
[self.currentNews.newsLink release];
[self.currentNews.newsGuid release];
blah...
blah...
blah...
}
}
And allocate your currentNews object in your init method (remove it from your didStartElement) and release it in your dealloc method. Oh, and #Louie is right, you need to look at your news as an array object which obviously has several currentNews, this currentNews or item is what your parser should be concerned about. After parsing all the element in "just one item" you add it to your news array when it reads the last element tag for that "one item", because after that your parser is simply going to loop and look for the next item.

NSXML parser read attributes

I have a element that is repeating and i need to read it's attributes and send them to the delegate
the xml is:
<special>
<day date="22/04/2011" name="Easter Friday">Closed</day>
<day date="23/04/2011" name="Easter Saturday">10:00-16:00</day>
<day date="24/04/2011" name="Easter Sunday">Closed</day>
<day date="25/04/2011" name="Anzac Day">13:00-17:00</day>
<day date="26/04/2011" name="Easter Tuesday">09:00-18:00</day>
</special>
i only get to past the last attributes for date and name to the delegate and i know why is this happening but i dont know how to fix it. can someone help me
here is my objective C code
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"special"]) {
storeAppDelegate.openingHoursSpecialDelegate = [[NSMutableArray alloc] init];
}else if ([elementName isEqualToString:#"day"]) {
openingHoursView = [[OpeningHoursView alloc] init];
openingHoursView.name = [attributeDict objectForKey:#"name"];
openingHoursView.date = [attributeDict valueForKey:#"date"];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"special"])
return;
if ([elementName isEqualToString:#"day"]){
[storeAppDelegate.openingHoursSpecialDelegate addObject:openingHoursView];
[openingHoursView release];
openingHoursView = nil;
}
}
openingHoursSpecialDelegate is a mutable array in the app delegate and OpeningHoursView is a NSObject that has name and date as strings in it in another class. They also get the value of the app delegate and it is also only the last read value for "date" and "name" attributes from the XML file .
I'm working with NSXML parser
so again my question is how to get "openingHoursView.name" and "openingHoursView.date" to write every value they get to openingHoursSpecialDelegate and not overwrite them as it happens now
I can't find anything wrong with the code. I've put the above code into a small test project (with minor changes to make it run standalone), and it runs fine for me.
Array (
"Easter Friday, 22/04/2011",
"Easter Saturday, 23/04/2011",
"Easter Sunday, 24/04/2011",
"Anzac Day, 25/04/2011",
"Easter Tuesday, 26/04/2011" )
Example project
You'll need to change the path I've hardcoded in the class test2AppDelegate, to point to a file containing the XML you posted above.
Already i have workout this problem in my project.But i am using libxml2.
The problem is (day node) you have to set the 5 different value to same key (day) thats why you get last attribute .

problem in copy string for other class

In my app I am sending a request to the web server and getting some results, then I am parsing this result and storing this result string into other class object string.
For example:
#interface GraphView : UIViewController<UITabBarControllerDelegate> {
NSMutableString *graphTempString;
}
#property(nonatomic,retain) NSMutableString *graphTempString;
#end
TSUClass .m
implementing NSURLConnection(),
connectionDidFinishLoading(),
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName
namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName
attributes:(NSDictionary *) attributeDict()
-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if( [elementName isEqualToString:#"statusTEResult"])
{
tempString=soapResults;
if (grpahCall == YES) {
graphViewController=[[GraphView alloc]init];
graphViewController.graphTempString=tempString;
[self.navigationController pushViewController:graphViewController animated:YES];
}
When I am debugging I can see the value of graphViewController.graphTempString but after going to GraphView, I am not able to see the values.
I hope some one know how to solve this issue.
Easy way to pass value.
[[NSUserDefaults standardUserDefaults]setObject:resultString forKey:#"resultString"];
[[NSUserDefaults standardUserDefaults] synchronize];
and in another class use this value like this
NSString *resultString=[[NSUserDefaults standardUserDefaults]valueForKey:#"resultString"];
or u may do it like this.
graphViewController.graphTempString=self.tempString;
can you try
2nClassObj.tempString =[NSString stringWithFormat:#"%#",resultString];
good luck
#Pooja i suggest you to try doing this by making a variable in AppDelegate class give your resultString to this variable and then fetch the value from this variable in your 2ndClass or in any class you want .....you will never get null value.
Lets suppose the object of your AppDelegate class is appDelegate and the variable which of NSString type is lets stringValue. Then in your class where you are getting the resultString do like this.
appDelegate.stringValue = resultString;
And in your 2ndClass class take the value from this variable like this.
tempString = appDelegate.stringValue;
You will get the data.....Hope you got my point.
Good Luck!
What happens if you add some NSLog statements?
if (grpahCall == YES) {
graphViewController=[[GraphView alloc]init];
NSLog(#"-%#-", tempString);
graphViewController.graphTempString=tempString;
NSLog(#"-%#-", graphViewcontroller.graphTempString);
[self.navigationController pushViewController:graphViewController animated:YES];
}
I would expect to see the same thing output twice? Can you tell me what you get in the console?