I have nearly 15 and more xml file inside of one folder if possible to parse all file one by one? I set path like this below if I want to parse multiple files. how can I set path of that folder file?
this code for single file xml parser it's working fine.
NSString *playlistfilePath = [[NSBundle mainBundle] pathForResource:#"CT8OkzhF8qmEYGe2" ofType:#"xml"];
NSData *playlistfileData = [NSData dataWithContentsOfFile:playlistfilePath];
NSString *playlistxmlFile = [[NSString alloc] initWithData:playlistfileData encoding:NSASCIIStringEncoding];
//parsing the XML
PlaylistXmlParser *playlistparser = [[PlaylistXmlParser alloc] init];
[playlistparser parseXMLFile:playlistxmlFile];
that all the XML files are having same structure and same element.
On the basis of the NSXMLParser object write the logic of the parsing:-
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
//check with switch or if else condition which NSXMLParser object is using this delegate.
}
As like above all the delegates of NSXMLParser have a parameter as an NSXMLParser object.
try this:
NSXMLParser *xmlParser = [[[NSXMLParser alloc] initWithData:playlistfileData]autorelease];
PlaylistXmlParser *parser = [[PlaylistXmlParser alloc] initXMLParser:#"xmlname"];
[xmlParser setDelegate:parser];
in PlaylistXmlParser.m file
- (PlaylistXmlParser *) initXMLParser:(NSString *)name {
[super init];
xmlname =name;
return self;
}
now in every methods in PlaylistXmlParser.m file :
if ([xmlname isEqualToString:#"xmlname"]) {
//store data
}
else if([xmlname isEqualToString:#"xmlname_1"]){
//store data
}
#moorthy use pathForResourcesType:inDirectory on NSBundle method to get array of paths, Then for every single path inside the array create an instance for the parser class and parse the file.
[[NSBundle mainbundle]pathForResourcesType:#"xml" inDirectory:"Your directory Path"]
This will return an array ...... Hope it helps you
Related
I'm using an xml parser, NSXMLParser to parse asn xml an return some url in an NSMutableArray.Everything is giong great except the fact that the french é is replaced by \U00e9.
Here is my code:
- (void)parseXMLFileAtURL:(NSString *)URL
{
NSURL *xmlURL = [NSURL URLWithString:URL];
xmlParser = [NSXMLParser alloc] initWithContentsOfURL:xmlURL];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[xmlParser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser setShouldResolveExternalEntities:NO];
[xmlParser parse];
}
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"catalogue"]) {
// clear out our story item caches...
currentCatalogue = [[Catalogue alloc] init];
}
if ([elementName isEqualToString:#"partenaire"]) {
// clear out our story item caches...
currentPartenaire = [[Partenaire alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"catalogue"]) {
// Add currentCatalogue to array
[catalogueList addObject: currentCatalogue];
NSString *urls=[catalogueList valueForKey:#"url"];
NSLog(#"Current catalogue: urls=%#", urls);
}
if ([elementName isEqualToString:#"partenaire"]) {
// Add currentPartenaire to array
[partenaireList addObject: currentPartenaire];
/*NSLog(#"Current partenaire: raison_sociale=%#, lat=%#, lng=%#", currentPartenaire.raison_sociale, currentPartenaire.lat, currentPartenaire.lng);*/
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
// Catalogue setup
if ([currentElement isEqualToString:#"id_model"])
currentCatalogue.id_model = string;
if ([currentElement isEqualToString:#"url"])
{
if (currentCatalogue.url)
{
currentCatalogue.url = [NSString stringWithFormat: #"%#%#", currentCatalogue.url, string];
// NSLog(#"Valoare url in data handler %#", currentCatalogue.url);
}
else
currentCatalogue.url = string;
}
}
Anyone any idea how to fix this?
TESTED CODE : 100 % WORKS
NSString* inputString =[NSString stringWithFormat:#"\40_TTRS_Coup\u00e9_TTRS_Roadster_Tarifs_20110428.pdf"];
NSLog(#"inputString is: %# \n\n",inputString);
OUTPUT:
inputString is: _TTRS_Coupé_TTRS_Roadster_Tarifs_20110428.pdf
Assuming your XML has an explicit encoding, as follows:
<?xml version="1.0" encoding="UTF-8"?>
then there are 2 problems you should address first. These may or may not fix your direct problem, but if not they will make it easier to narrow in on the problem you are seeing. Here are the problems you should fix:
Remove the code that calls 2 different initializer methods on a single NSXMLParser instance. That will have undefined results and its impossible to know what is going on until you fix that.
Change how you implement the parser:foundCharacters: method. As NSXMLParser documentations states, this may be called multiple times for a given set of characters within an XML element. Instead of just accepting the string and storing its value away, your delegate class should have a mutable character buffer that you append to each time foundCharacters gets called. Then in parser:didElementEnd you can grab the contents of the buffer and do what you need to with that value.
Try it out with these fixes and see if it works. If not, update your post with a corrected version of your code and it might be more obvious what the problem is.
I have a xml file in following format.
<Category id="CIBA_VISION" image="Choose_Page\CON_PNG\Ciba_Vision.png">
<Product id="CON_CIBA_01" image="Buy_Page\Eye_CON_PNG\CIBAVision\List_01.png">
<Detail image="Buy_Page\Eye_CON_PNG\CIBAVision\Buy_01.png"/>
</Product>
where images contains image path in specified folder which is in resource folder of project.
My question is: After parsing this xml file, will the image tag pick the values from the folder or it will show only path after parsing.
Thanks in advance.
NSString *imaegeString = #"Ciba_Vision.png";
NSArray *pathComponents = [imaegeString componentsSeparatedByString:#"_"];
NSString *imageName=[pathComponents lastObject];
UIImage *img8 = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:imageName]];
try this code
It will only contain the values you see there, except you add the base to URLs while parsing yourself.
And picking completely depends on your context, how do you like the code to pick?
yes you can get the image by the following code in your imageView You can try this:-
NSString *imaegeString = #"Choose_Page\CON_PNG\Ciba_Vision.png";
NSArray *pathComponents = [imaegeString componentsSeparatedByString:#"_"];
NSString *imageName=[pathComponents lastObject];
UIImage *img8 = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:imageName]];
Hope this might help you...If this work you can do same for another strings in your parsing...
you ll get only path after parsing it wont do anything with that path.we have use that path and do our work thats it
some sample is
-(void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString: #"Detail"]){
//get all the attributes of from the dictionary(attributeDict)
}
}
I am using the NSXMLParser to get new RSS stories from a feed and am displaying them in a UITableView. However now I want to take ONLY the images, and display them in a UIScrollView/UIImageView (3 images side-by side). I am completely lost. I am using the following code to obtain 1 image from a URL.
NSURL *theUrl1=[NSURL URLWithString:#"http://farm3.static.flickr.com/2586/4072164719_0fa5695f59.jpg"];
JImage *photoImage1=[[JImage alloc] init];
[photoImage1 setContentMode:UIViewContentModeScaleAspectFill];
[photoImage1 setFrame:CGRectMake(0, 0, 320, 170)];
[photoImage1 initWithImageAtURL:theUrl1];
[imageView1 addSubview:photoImage1];
[photoImage1 release];
This is all I have accomplished, and it works, for one image, and I have to specify the exact URL. What would you recommend I do to accomplish this?
Further to my other answer, which uses some helper classes and kinda assumes you're storing stuff with Core Data, here's a pure NSXMLParser way to do it.
In this example I'm assuming you have three UIImageViews setup with tags (100,101,102) so we can access them. First off, the code that starts the parser:
// Set the URL with the images, and escape it for creating NSURL
NSString *rssURLString = #"http://feeds.gettyimages.com/channels/RecentEditorialEntertainment.rss";
NSString *escapedURL = [rssURLString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *rssURL = [NSURL URLWithString:escapedURL];
// rssParser is an NSXMLParser instance variable
if (rssParser) [rssParser release];
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:rssURL];
[rssParser setDelegate:self];
success = [rssParser parse]; // return value not used
At this point the parsing starts and NSXMLParser will fire off calls to it's delegate methods as it finds different start and end elements in the XML.
In this example I am only writing the didStartElement method:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// look for an attribute called url
if ([attributeDict objectForKey:#"url"]) {
currentString = [attributeDict objectForKey:#"url"];
NSLog(#"Image URL: %#", currentString);
NSString* escapedURL = [currentString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:escapedURL]]];
UIImageView * tmpImageView = (UIImageView*)[scrollView viewWithTag:100+imageCount];
[tmpImageView setImage:image];
NSLog(#"images found: %d", imageCount);
imageCount++;
if (imageCount>2) [rssParser abortParsing];
}
}
Here we look to see if the attributeDict (an NSDictionary object) contains a url attribute. If so, we grab it into currentString and then escape it, just incase it has characters that NSURL will barf on. Then we create an image from that URL and set the appropriate UIImageView image based on the tag numbers. imageCount is a counter; once we've done three images we tell the NSXMLParser to abort parsing the XML.
If your XML puts the URL inside element tags like:
<image>http://example.com/image.jpg</image>
You'll need to do a bit more work with didEndElement and foundCharacters. See the quite excellent Introduction to Event-Driven XML Programming Guide for Cocoa.
I knocked together a quick and dirty app to demo this, you can grab it here.
it sounds like you need to first identify the xml tag that identifies the images in your xml document. you should be able to do this by typing whatever API call you're using into a browser address bar.
once you've done that you can make an array of image urls from the nsxmlparser delegate method that receives new data.
once you have the array of image url's you can do something similar to what you are doing above except that you would use NSURL *theUrl1=[myArray objectAtIndex:...
you can arrange the images just by changing their centre location: image.center = CGPointMake(160,240)..
hope that helps. there are apple docs for nsxmlparser.
You can also try dictionary implementation while fetching data from API call. First you have to identify xml tag that identifies images in xml document, then you can assign each image with its corresponding story as image's key into a dictionary. It will make sure that for particular story only its associated image will be displayed. Then u can use this information later in your application as the requirement varies.
NSMutableDictionary *mutDict = [[NSMutableDictionary allloc]init];
if([elementName isEqualToString:#"story_image"])
{
[mutDict setObject:currentImage forKey:currentStory];
}
I want to suggest you to use JSON instead of xml as it is lightweight data-interchange
format. It would save lot of formatting and effort also.
You can visit this page
http://code.google.com/p/json-frame
It is definitely going to help you.
You have to just download the framework and then use in your application.
To get the live data you have to do same thing as in XMLParsing
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSDictionary *JDict = [jsonString JSONValue];
or
NSArray * JArr = [jsonString JSONValue];
depending upon what your data-feed contains.
I've been using NSXMLParser myself and storing the results using CoreData. I use a version of Björn Sållarp's Parser class from his CoreData example code.
My images end up as NSData/Binary in a SQLite database, but they might just as well get put into an array of UIImage for immediate display.
Extract from Parser.m: (from Björn Sållarp)
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"imagetag"])
{
UIImage *newImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:currentString]]];
NSData *imageData = UIImagePNGRepresentation(newImage);
[currentSearchResult setImage:imageData];
currentString = nil;
return;
}
Called from my view with:
NSString *searchURL = #"http://www.feedurl.com/feed/address/feed.xml";
NSURL *xmlURL = [NSURL URLWithString:searchURL];
Parser *xmlParse = [[Parser alloc] initWithContext:managedObjectContext];
[xmlParse parseXMLFileAtURL:xmlURL parseError:&parseError];
That code assumes your XML document contains image URLs with the tag format:
<imagetag>http://example.com/path/to/image.png</imagetag>
Even if you're not using CoreData, working through the example at that link would be instructional for processing XML with NSXMLParser.
I am new to iphone development .I want parse an image url from a xml file and display it in a RSS feed.There are three image url but i want to retrieve only one url and display it.
<entry>
<id>xxxxx</id>
<title>xxx xxxx xxxx</title>
<content>xxxxxxxxxxx</content>
<media:group>
<media:thumbnail url="http://tiger.jpg"/>
<media:thumbnail url="http://lion.jpg"/>
<media:thumbnail url="http://elephan.jpg"/>
</media:group>
</entry>
for parsing it
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"entry"]) {
entry = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
currentDate = [[NSMutableString alloc] init];
NSLog(#"inside image1 ");
}else if([elementName isEqualToString:#"media:thumbnail"])
{
NSString* myUrl = [NSString stringWithString:[attributeDict objectForKey:#"url"]];
}
}.
I want to retrieve only tiger image.Please help me out.Thanks.
In this perticular instance you could set a class variable instead of the current local myUrl and once you get a value in it. In the code below this assumes you never initialize myURL anywhere else.
if (myURL == nil)
myUrl = [attributeDict objectForKey:#"url"];
However this will only work the way you expect if you always want the first thumbnail URL. Unless you have some guarantee (which you haven't mentioned) that you will always want the first URL then there really isn't anything you can do to catch cases when you don't want the first URL since all of the thumbnail URLs tags and attributes are the same save for the URL.
I am working with an API where I get a response back this this, and I want to parse the integer ID out of it:
<?xml version="1.0"?>
<trip>328925</trip>
How would you parse this? I have some really fragile code I want to get rid of, and I'd appreciate some advice:
if ([[response substringWithRange:NSMakeRange(0, 21)]
isEqualToString: #"<?xml version=\"1.0\"?>"]) {
self.tripId = [response substringWithRange:NSMakeRange(28, response.length-35)];
}
I don't think I need an XML parsing library for this task!
I would use an XML parser. Using an XML parser really is the best way to parse XML.
It's not that hard to do either:
// Parser Delegate
#interface ParserDelegate : NSObject {
int inTripElements;
NSMutableString* trip;
}
#property (readonly) NSMutableString* trip;
#end
#implementation ParserDelegate
#synthesize trip;
- (id) init {
if (![super init]) {
[self release];
return nil;
}
trip = [#"" mutableCopy];
return self;
}
- (void) parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"trip"]) {
++inTripElements;
}
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (inTripElements > 0) {
[trip appendString:string];
}
}
- (void) parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"trip"]) {
--inTripElements;
}
}
#end
// Parsing
NSString* toParse = #"<?xml version=\"1.0\"?>"
"<trip>328925</trip>";
NSData* data = [NSData dataWithBytes:[toParse UTF8String]
length:strlen([toParse UTF8String])];
ParserDelegate* parserDelegate = [[ParserDelegate alloc] init];
NSXMLParser* parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:parserDelegate];
[parser parse];
[parser release];
NSLog(#"trip=%#", parserDelegate.trip);
[parserDelegate release];
If you really don't want to use an XML Parser to create a proper object why not use the regular expression <trip>\d*</trip> to match the element? Then you can get the integer part by removing the start and end tag and parsing to ensure correct as with any string.
Here is a handy place for testing regular expressions; http://regexlib.com/RETester.aspx
Check out 'NSScanner'. It would be perfect for this.
You should use an XML library for this as there are many cases where the code will change
For example in this case what happens if
The <?xml declaration is not sent or the encoding changes from UTF-8
or somone adds a space before the trip element
In all these cases the provider of the file can say the file is correct
etc.
with the XML parsing all this has been done and your code is more robust
Also in this case the code to parse and find is quite simple.