xpath Table Contents into an array - objective-c

How would I use xPath under the hpple Objective-C wrapper to extract the elements out of this table. Ideally I would like to put the addresses and prices into an array or dictionary.
I have been attempting to use the hpple objective c wrapper to pull the data out of the table located here: http://www.gaspry.com/index.php?zipcode=02169&action=search but haven't succeeded in getting the correct xpath query to pull out the information. Ideally, I would like to store this information in a set of arrays one, for addresses, and one for each of the prices. I am stuck on how to retrieve all of the information from the table and am unsure that my xPath is correct
My Code Thus Far is:
- (void)viewDidLoad {
[super viewDidLoad];
//Url Information
NSString *urlAddress = #"http://www.gaspry.com/index.php?zipcode=02169&action=search";
NSURL *url = [NSURL URLWithString:urlAddress];
NSData *htmlData = [[NSData alloc] initWithContentsOfURL:url];
//Start Parsing
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *elements = [xpathParser search:#"//tBody[tr]"]; // get the table information
TFHppleElement *element = [elements objectAtIndex:0];
NSString *bodyTag = [element content];
NSLog(#"%#", bodyTag);
[xpathParser release];
[htmlData release];
}

One advice, a search path is case sensitive so make sure you use right one.
search query for :
#"//tbody//tr[1]//td[1]"
will get you address and change column "td[#]" to access other things you may want to store.
I'm not sure but address won't be parse correctly, that is, above search query will result after
tag but won't give you content before tag.
Hope this help :D

Related

Extracting Text from url Xcode?

I am new to Objective C.
I was trying to extract text from a webpage and display it in a textView;
Except for when I run the app it appears to show html instead of the article.
NSURL *URL = [NSURL URLWithString:[self.url
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
NSData *theData = [NSData dataWithContentsOfURL:URL];
NSString *content = [[NSString alloc] initWithData:theData encoding:NSStringEncodingConversionAllowLossy];
_viewPage.text = content;
The viewPage is the textview itself. How do I extract the text only?
You have not included any code to extract the text from the web page. When you run "dataWithContentsOfURL" and it's a web page, then, as you have seen, you get the whole page.
To extract the data you need to process the results. In a simple case you can get the text with some string manipulation. In more complex cases you should look for a library which will parse the whole page for you. You can then access the parsed structure to get the content that you want.
Look here for an example of the simple case;
http://natashatherobot.com/html-css-parser-objective-c/
There are libraries for the more complex case.

How to check if NSURL contains NSString null?

I use the following code to get a NSString from a NSDictionary and then cast it into NSUrl:
NSURL * url = [NSURL URLWithString:[self.item objectForKey:#"website"]];
The NSDictionary self.item comes from a web server and it's correctly filled using JSON data. All the other objects inside the NSDictionary work perfectly fine.
But sometimes the web server passes a website url with the text "null" because the object has no website filled in. From debugging i learned that the NSURL object can contain a url with the text "null". But how do i prevent this, or how can i write an if statement that checks this?
I tried the following:
NSString * niks = [eventUrl absoluteString];
if(niks == #"null")
{
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Event" message:#"Event heeft geen website" delegate:nil cancelButtonTitle:#"Oke" otherButtonTitles:#"Oke", nil];
[message show];
}
else
{
[webView loadRequest:[NSURLRequest requestWithURL:eventUrl]];
NSLog(#"%#",eventUrl);
}
But this doesn't work, it always passes the url directly to the webview. Can someone set me in the right direction?
Your comparison;
if(niks == #"null")
only compares if the pointers are equal (i.e. if the two are the same string object instance). Since one is a constant and the other is created dynamically from JSON fetched from the server, it's very unlikely.
To compare the content of two strings, you should instead do;
if([niks isEqualToString:#"null"])
For the link thirsty, here is the [NSString isEqualToString:] documentation.
To do string comparison, you need to do [niks isEqualToString:#"null"], that's why the first condition is broken.
You can also use [niks RangeOfString:#"null"];
I believe you can do this:
id str = [self.item objectForKey:#"website"];
if([str isMemberOfClass[NSNull class]]) {
... its null
}
The JSON convertors all change null to a NSNull object (in my experience).
I am not 100% clear of my memory, but I encountered a situation where [NSDictionary objectForKey:] actually returned NSNull class instance instead of "null" string.
If this is the case, you can check the class of [self.item objectForKey:#"website"] by using isKindOfClass method.

Retrieving a specific data

I am new to xcode.. and I would love to learn about retrieving data from XML.. This is a draft code that I have been stucked with for days.. I manage to display a list of XML codes
XML CODE:
<find>
<set_number>038881</set_number>
<no_records>000138874</no_records>
<no_entries>000007000</no_entries>
</find>
However, now I have some difficulties in retrieving only the set_number from this xml... The URL I have left it blank due to confidential purposes.. so dont mind about it.. The last two codes has resulted my app to force close.. Help!!
NSString *URL = [NSString stringWithFormat:#""];
NSMutableData *receivedData = [[[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:URL] ]autorelease];
NSString *theRecord = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
NSString *path = [theRecord valueForKey: #"set_number"];
NSLog(#"File Data: %#", path);
I tried to add in this code at the bottom instead..
if ([theRecord isEqualToString:#"no_records"]){
NSLog(#"Contents of URL: %#", theRecord);
}
Then I also trying to debug my codes.. No error shown.. instead they display 0 for the output.. and I am wondering is it because my no_records is an integer?? But I have assign the record as a string.. is that why they couldnt display?
I tried to add in this code at the bottom instead..
`if ([theRecord isEqualToString:#"no_records"]){
NSLog(#"Contents of URL: %#", theRecord);
}`
Then I also trying to debug my codes.. No error shown.. instead they display 0 for the output.. and I am wondering is it because my no_records is an integer?? But I have assign the record as a string.. is that why they couldnt display?? Please help!!
To parse your XML use the NSXMLParser class.
NSString *path = [theRecord valueForKey: #"set_number"];
theRecord is a NSString instance that can not use valueForKey.
You should parse your xml string first and get the content you want from tag.
Or you should get substring in your string.

How do i grab numbers from a Table on a website in my Cocoa App?

Ok this is a more specific version of my last question.
So on a website there exists some data that is coded in HTML into a table.
In my Cocoa app, I want to download the html code of the website and then read through the html and snag the data from it. I was hoping someone could point out some useful classes/methods for accomplishing the retrieval of the website and putting it into some format where I can read through the code in my program?
Thanks in advance!
Try using hpple, it's an HTML parser for ObjC.
here's an example using it:
#import "TFHpple.h"
NSData *data = [[NSData alloc] initWithContentsOfFile:#"example.html"];
// Create parser
xpathParser = [[TFHpple alloc] initWithHTMLData:data];
//Get all the cells of the 2nd row of the 3rd table
NSArray *elements = [xpathParser search:#"//table[3]/tr[2]/td"];
// Access the first cell
TFHppleElement *element = [elements objectAtIndex:0];
// Get the text within the cell tag
NSString *content = [element content];
[xpathParser release];
[data release];

parsing JSON using objective C?

I have spent 1 week studying objective C. Now I am quite confused at the dealing with data part.
My friend gave me a link
http://nrj.playsoft.fr/v3/getQuiz.php?udid=23423455&app=2
and ask me write a class to parse this JSON. I had no clue what parsing JSON means. but I have gone online and looked up. I could understand a basics of it and then I impletemented a punch of code to parse this JSON. Which is:
-
(void)parseURL
{
//create new SBJSON object
SBJSON *parser = [[SBJSON alloc] init];
NSError *error = nil;
//perform request from URL
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://nrj.playsoft.fr/v3/getQuiz.php?udid=23423455&app=2"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
NSDictionary *results = [parser objectWithString:json_string error:&error];
// array just for the "answer" results
NSArray *quizes = [results objectForKey:#"quiz"];
NSDictionary *firstQuiz = [quizes objectAtIndex:0];
// finally, the name key
NSString *extract = [firstQuiz objectForKey:#"extract"];
NSLog(#"this is: %#", [extract valueForKey:#"extract"]);
}
This is at the implementation file, but in the header file I could not declare any variables, it will print out some errors. I tried to run this, there is no errors, but I am not sure this code is correct or not. And my friend asked me to write a class into an existing project. I don't know what needs to be modified and what not. I am so blur right now. Could anyone pro in this give me a hand. ?
My sincere thanks.
Thanks for reply. I have downloading and added the JSON framework ealier too. I am just not sure where to begin and where to end, meaning the step I should do when I add JSON framework into it. I could understand the syntax but I am not sure about the steps I should do. I am a newbie in this.
If you support iOS 5.0+, you should use built-in NSJSONSerialization.
It is faster than TouchJSON.
You could just use TouchJSON: http://code.google.com/p/touchcode/wiki/TouchJSON
Or you could use this one: http://code.google.com/p/json-framework/
I'm sure there are others. I use TouchJSON... it's fast and has a good API.
I recommend working through Ray Wenderlich's MapKit tutorial, especially if you are a newbie. It covers several common iOS development issues, including parsing JSON data.
http://www.raywenderlich.com/2847/introduction-to-mapkit-on-ios-tutorial
"The Implementation" section is where his JSON feed is retrieved and then in "Plotting the Data" he uses the SBJson library to parse it.