how to use my imported xml in my objective-c project? - objective-c

i have this demo xml file:
<trains>
<israel>
<Lehavim>
<lat>31.370201</lat>
<lon>34.798336</lon>
</Lehavim>
<tel-aviv>
<lat>32.073847</lat>
<lon>34.793358</lon>
</tel-aviv>
</israel>
</trains>
loaded to my project using this code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [[NSURL alloc] initWithString:#"http://www.amotech.co/trains.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[xmlParser setDelegate:self];
BOOL success = [xmlParser parse];
if(success)
NSLog(#"success");
else
NSLog(#"Error");
}
i need to get my xml into a UITableView - i want to only to show the name of the train station (for example: "Lehavim" in the TableView.
and after i chose one of my table view items - i want to load the current lat and lon data into double objects.
i would like you to help me with this please.
thanks, amir.

Sounds like you need to get the fundamentals first:
This link takes you to the gory details of NSXMLParser directly from apple.
This link shows a fantastic example of how to use the NSXMLParser.
This link offers some simple examples for adding objects to an array.
This link is a very nice tutorial on UITableViewController.
You will need to provide a little elbow grease.
Quite Tip
To save yourself some headaches and to add flexibility to your xml, I recommend you modify your xml structure such that you aren't using your element names as values.
Change:
<trains>
<israel>
<Lehavim>
<lat>31.370201</lat>
<lon>34.798336</lon>
</Lehavim>
<tel-aviv>
<lat>32.073847</lat>
<lon>34.793358</lon>
</tel-aviv>
</israel>
</trains>
to:
<trains>
<train>
<name>israel</name>
<location>
<name>Lehavim</name>
<lat>31.370201</lat>
<lon>34.798336</lon>
</location>
<location>
<name>tel-aviv</name>
<lat>32.073847</lat>
<lon>34.793358</lon>
</location>
</train>
</trains>

Related

How to populate a UITableView from a remote .plist file

Sorry if this has been asked many times before, but nothing seemed to help my issue.
I have set up my app to work perfectly reading from local .plist files from within the app itself for testing purposes, but for the app to be of any use, I need to be able to update it on a web server and load it remotely.
Here is my current code for local plists.
How would I amend this with minimum changes elsewhere in the app?
Many thanks in advance.
- (void)viewDidLoad
{
[super viewDidLoad];
//Create a dictionary with the contents of Squad.plist
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Squad" ofType:#"plist"]];
//Fill the Squad array with contents of dictionary under the key "Players"
[self setSquad:(NSArray*) [dictionary objectForKey:#"Players"]];
//Reload the table data
[[self tableView] reloadData];
[[self navigationItem] setPrompt:nil];
}
You will need to first download your remote .plist while showing a loading or something, and after it's downloaded, use it locally the same way you are doing now. There's no way to read it remotely.

Parse XML and generate UI in UIWebView iPad App

I will receive an XML from Server, and have to parse the xml file, and based on that have to populate textbox, listbox etc(a form) in UIWebView.
I know XML parsing for iOS using NSXML, I do not know how to fire events to generate Form/UI at runtime.
Any tutorials or idea pls.
If you have created your HTML as a NSString already, you can load it into the UIWebView by using the method loadHTMLString:baseURL:. For example:
NSString *htmlString = [[NSString alloc] init];
//Download XML, parse it and turn it into HTML.
[myWebView loadHTMLString:htmlString baseURL:nil];
//if you have to do any thing else to the HTML string do it here
[htmlString release];
Changing the htmlString after calling loadHTMLString:baseURL: won't update the UIWebView. You will need to call the method again, sending the modified string.
If you need further help, comment below and I'll edit my answer or comment back.

Cocoa/Obj-C simple XML file reader - need help

I asked a question yesterday about a little app that I would like to make for OSX with Cocoa/Obj-C (Xcode).
The princip is easy:
Got an XML file like this one:
<?xml version="1.0" ?>
<Report>
<Date>20110311</Date>
<Title>The Title</Title>
<Description>Description sample<Description>
</Report>
When the app is opened, there is a window with three text fields.
When a file is loaded (File -> Open) the three text fields get the value of what is in the XML elements. For my example it will be:
TextFields 1 => 20110311TextFields 2 => The TitleTextFields 3 => Description sample
And that's it!
As you can see in my description, it's maybe easy...
But I tried a lot of things, I didn't successed :/
I'm a newbie in Cocoa developpment and there's a lot of dedicated things that I don't understand like how can I make links between CODE & GUI...
Now here is my demand:
If someone could make me an Xcode project similar to my example above, for see what's wrong with my different trys, or explain me how this app can be done (with codes examples)...
I've spend 4 long days on that project but didn't have results :(
Help... :(
Miskia
Two little things to consider:
You should definitely read into the Objective-C / Cocoa documentation.
Otherwise you will never be able to program something yourself.
In the end this will save you lots of time struggling with problems like these.
The things you ask are just the very basics of programming.
(Besides the XML part)
You should never ask people to write complete applications.
People on Stack Overflow are more then willing to help with specific problems,
but they do not work for you.
That being said, here my actual answer:
The XML code you provided contains a syntax error:
The second <Description> should be </Description>
For my example code below I used the following XML file:
<?xml version="1.0" ?>
<Report>
<Date>20110311</Date>
<Title>The Title</Title>
<Description>Description sample</Description>
</Report>
This quickly written example does everything you need.
Create a new application with XCode and open the .....AppDelegate.m file.
Simply paste the Objective-C code mentioned below within the following function:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Paste Here
}
Next click 'Click build and Run'.
Select your file within the NSOpenPanel and click the open-button.
Now you should see a simple dialog with the results.
Hopefully this helps you understand how to parse the XML file.
I can imagine 4 days of struggling must be unpleasant :)
The Objective-C sample code:
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
NSArray *fileTypes = [NSArray arrayWithObjects:#"xml",nil];
NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ];
if(result == NSOKButton){
NSString * input = [openPanel filename];
NSXMLDocument* doc = [[NSXMLDocument alloc] initWithContentsOfURL: [NSURL fileURLWithPath:input] options:0 error:NULL];
NSMutableArray* dates = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* titles = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* descriptions = [[NSMutableArray alloc] initWithCapacity:10];
NSXMLElement* root = [doc rootElement];
NSArray* dateArray = [root nodesForXPath:#"//Date" error:nil];
for(NSXMLElement* xmlElement in dateArray)
[dates addObject:[xmlElement stringValue]];
NSArray* titleArray = [root nodesForXPath:#"//Title" error:nil];
for(NSXMLElement* xmlElement in titleArray)
[titles addObject:[xmlElement stringValue]];
NSArray* descriptionArray = [root nodesForXPath:#"//Description" error:nil];
for(NSXMLElement* xmlElement in descriptionArray)
[descriptions addObject:[xmlElement stringValue]];
NSString * date = [dates objectAtIndex:0];
NSString * title = [titles objectAtIndex:0];
NSString * description = [descriptions objectAtIndex:0];
NSString *output = [NSString stringWithFormat:#"Date: %#\nTitle: %#\nDescription: %#", date, title, description];
NSRunAlertPanel( #"Result", output, #"OK", nil, nil );
[doc release];
[dates release];
[titles release];
[descriptions release];
}
Here some additional information:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/XMLParsing/Articles/UsingParser.html
Sample project:
http://dd5.org/static/XML.zip
How to create a project like above:
- Create new project
- Add code to the header (.h) and implementation (.m) files
- Design the main window
- Finally add the correct bindings
See images below how to add the bindings (already done in the sample project).
Right-click on the App Delegate drag to the NSTextFied (Picture 1).
Release the button and select the correct entry in the ray menu (Picture 2).
Feel free to look at two easy XML parser classes I created.
http://www.memention.com/blog/2009/10/31/The-XML-Runner.html
Source with projects are available at github
https://github.com/epatel/EPXMLParsers

Multiple NSXMLParser calls

I use an API call which returns an XML file. I need to use the same multiple times.
For e.g. on Click of Search button, call http://xyz.com/s1/?para1=srch
Then in a different view, call http://xyz.com/s2/?para2=set2
How should I implement the same? I mean should the XMLParser file be common for both the requests and just the if..else element names should be mixed in a single implementation of parser:didEndElement?
Please help me with an example.
Sure, you can re-use a parser if the page elements are the same. Just make a method in your parser's class that you can feed a location or xml file, and have it parse that file. Something like:
-(void)parseForecast:(NSData *)data; {
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:self];
[parser parse];
[parser release];
}
should do the trick.

How to get a DTD's public and system IDs with NSXMLParser

I'm trying to retrieve the public and system IDs for a DTD in an XML document via NSXMLParser. While NSXMLParser in principal offers publicID and systemID selectors they don't seem to work for me. The doctype tag looks like this:
<!DOCTYPE Article PUBLIC "-//SoftQuad Software//DTD Journalist v2.0 20000501//EN" "file:///C:/Program%20Files/Corel/XMetaL%204/Author/Rules/journalist.dtd">
Here's my code (the file was opened via NSFileHandle's readDataToEndOfFile:
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:self];
BOOL parseSuccessful = [parser parse];
In the delegate's parserDidStartDocument: I try to access the IDs:
NSLog(#"%# : %#", [parser publicID], [parser systemID]);
But I only see
(null) : (null)
From the documentation:
You may invoke this method once a parsing operation has begun or after an error occurs.
So I'd think this should work already in parserDidStartDocument: but I tried to call these selectors in different delegate methods (like parser:didStartElement:namespaceURI:qualifiedName:attributes: but without success.
Any ideas what I'm doing wrong?
You might try out another parser.
http://www.robbiehanson.com/expat.html provides a drop-in replacement for NSXMLParser based on expat.
You might also find this article interesting, comparing the performance of various XML parsers on the iPhone.
http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project