how to read content of an XML file from NSOpenPanel - objective-c

I am trying to copy the content of an XML file after selection from NSOpenPanel in cocoa.
So lets say this XML file could be any where on desktop or other directories. Once I get the file Path, I am trying to read/copy the content to an NSMutableData like following.
I have filePath:
NSString* filePath = [files objectAtIndex:0];
e.g.: file://localhost/Users/Me/Documents/XMLFiles/FileA.xml
Trying to get the content and copy to an NSMutableData
xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
or
xmlData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:filePath]];

If you truly want the data under NSMutableData form then the following should help you:
NSMutableData *theData = [NSMutableData dataWithContentsOfURL:[[theOpenPanel URLs] objectAtIndex:0]];
But I don't think that would be very useful. Why have xml as raw data? Mutable at that!!
Are you looking for the string so you can manually look at the text document?! Then perhaps this is what you're looking for : NSString's stringWithContentsOfFile:encoding:error
Perhaps you want to parse it afterwards?! Then I'd suggest reading on NSXMLParser.

Related

Initializing Nsdata with Nsdata as a string

I have some NSData output that I would like to convert to a string.
NSString * test = [NSString stringWithFormat:#"myfile.txt];
NSData *myData = [[NSData alloc] initWithContentsOfFile:(#"%#", test)];
This NSData was saved to a file, it looks like : 21fa9731 27c67c00 da1c3349 d82470eb 56f97b88 559f406c 6abecbb7 de020007 47a4541d 99c9c5e7 883f8bf1 165fba39
Do you know a way to get this string back as it was in "myfile.txt" ?
Thanks !
If data file somewhere on HDD (not in app bundle) you must provide full path to your data file.
NSString * test = [NSString stringWithFormat:#"myfile.txt];
NSData *myData = [[NSData alloc] initWithContentsOfFile:(#"%#", test)];
NSString* myString = [NSString alloc]initWithData:myData
encoding: NSUTF8StringEncoding];
Choose encoding in which you save you data file.
I don't know what your problem ist. You could share with us how the file was written so that we can get a bit closer.
However, you are doing much too complicated and therefore error prone. The following would to for reading a file with a constant name fo myfile.txt.
NSData *myData = [[NSData alloc] initWithContentsOfFile:#"myfile.txt"];
Frankly I don't even know in which directory myfile.txt is expected to be. And there are of course much better ways to deal with constant literals than using literals directly in the code.
BTW, what do you actually receive in myData? null?
(This is more of a comment than an answer, but the formatting is much better in answers.)

Calling multiple XML files

In my application(iPad application) I have 5 folders and inside of each folder i have one XML file. My question is, How can I call all .xml files, in my appDelegate
I have file1.xml, file2.xml, file3.xml, file4.xml,file5.xml (it's a requirement)
for call or adding Path for file1 xml I have this code:
NSString *xml = [[NSBundle mainBundle] pathForResource:#"file1" ofType:#"xml"];
NSData *Data = [NSData dataWithContentsOfFile:xml];
NSXMLParser *Parser = [[NSXMLParser alloc] initWithData:Data];
file1 *parser = [[file1 alloc] initXMLParser];
but how can I have all 5 in my appDelegate class?
and do I need to create specific parser class for each or since all information and tags are the same I just need to add all in my appDelegate
EDIT:
I have to call them from their folder I cann"t change the structure for example
Folder1/file1.xml
Folder2/file2.xml
Folder3/file3.xml and so on
Yes, you need to instantiate an NSXMLParser object for each XML file you're parsing. The simple way to load the XML files is as kimsnarf says: use a for loop and load them in order. If they're in the bundle (which they appear to be), I'd stick them in a specific path under "Resources," like "Resources/SpecialXMLJunk" and just load them by iterating over the results of something like URLsForResourcesWithExtension:subdirectory: (used to get the XML files out of "Resources/SpecialXMLJunk"). So, pseudocode-ish, probably something like this:
NSArray *xmlResourceURLs = [mainBundle
URLsForResourcesWithExtension: #"xml"
subdirectory: xmlResourcesPath];
foreach (NSURL *xmlURL in xmlResourceURLs)
[self loadJunkXMLAtURL: xmlURL];
Create a for-loop and load/parse the files one by one. You should store the parsed data somewhere anyway (in a cache or database) so you don't need to hold on to the files and parsers after parsing. Retrieve data from the cache/database instead.

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.

Embedding XML to iOS application

I'm making my first game in iOS and I need to load some levels that are stored as XML. Level files are stored locally and everything works fine from emulator. However, since XML is loaded in the runtime when i try to test my game on an actual device it can't find the XML files since they are not actually part of the app.
I'm coming from Flash background so I might have a wrong idea how this is done on iOS but I need to somehow bundle those XML files with the app, or embed it in the code somehow? Is this possible?
Thanks a lot :)
Well The code to look up your app bundle for the specified file is
NSString *path = [[NSBundle mainBundle] pathForResource:#"fileName.xml" ofType:nil]
NSURL *xmlURL = [NSURL fileURLWithPath:path];
[[NSXMLParser alloc] initWithContentsOfURL: xmlURL]
Hope this helps you...
You could add the XML file to your project and run time read it up with something like this
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *myPath = [myPathList objectAtIndex:0];
NSError **err;
myPath = [myPath stringByAppendingPathComponent:fileName];
if([[NSFileManager defaultManager] fileExistsAtPath:myPath])
text = [NSString stringWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:err];
You could consider using JSON in instead of XML. At least to my knowledge the available XML parsers are not nearly as simply to use as SBJson for instance (https://github.com/stig/json-framework/)
Here is my solution in Swift 3.0. In addition to the code, you'll need to add your xml file as a data set in your Assets.xcassets. Do this by creating a new Data Set, giving it any name, and then dragging the xml file from the finder to your newly created data set. When you reference the file in your code, you'll use the file name of the file, and not the name of the data set.
var parseResults = false
if let path = Bundle.main.path(forResource: fileName, ofType: ".xml") {
let url = URL(fileURLWithPath: path)
if let xmlParser = XMLParser(contentsOf: urlToFile) {
xmlParser.delegate = self
parseResults = xmlParser.parse()
}
}

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];