how to limit parsing in iphone? - iphone

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>
<entry>
<id>xxxxx</id>
<title>xxx xxxx xxxx</title>
<content>xxxxxxxxxxx</content>
<media:group>
<media:thumbnail url="http://parrot.jpg"/>
<media:thumbnail url="http://peacock.jpg"/>
<media:thumbnail url="http://sparrow.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"])
{
if(myUrl==nil){
NSString* myUrl = [NSString stringWithString:[attributeDict objectForKey:#"url"]];
}
}
}.
I want to retrieve only tiger and parrot image.But i get tiger twice.Please help me out.Thanks.

Simply keep a flag in your parser delegate that you reset when you see <media:group>. Then every time you see a <media:thumbnail> you get. Then every time you get a <media:thumbnail>, check if the flag has been set. If not then this is the first one, so you take the data and set the flag. When you see the next <media:thumbnail> you ignore it because the flag has been set.
In your case, myUrl is the flag. So simply reset it to nil every tie you see the <media:group>.

When you start parsing your entry element reset myUrl variable to nil - so you will parse "media:thumbnail" once for each 'entry' element

Related

NSXMLParser replaces é characters with \U00e9

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.

how to parse xml

i am having an output xml which looks something like this,
<?xml version="1.0"?>
<root>
<apple><apple1>A</apple1></apple>
<ball><ball1>B</ball1></ball>
<cat><cat1>C</cat1></cat>
<dog><dog1>D</dog1></dog>
<ele><ele1>E</ele1></ele>
<root>
i am using NSXmlParser, i m confused, is tgis a gud xml structure?>//
secondly i dont knw how to parse this xml , i mean how should i write condition in parser didSTart and didEndElement ???
i m not to able properly navigate through each node, from apple to ele. i just want to assign the returned value of say apple to a string.
same for each node.
i m so confused in if / else condition.
Suggestions are always appreciated
regards
You need to have exactly one root element, like so:
<?xml version="1.0"?>
<root>
<apple><apple1>A</apple1></apple>
<ball><ball1>B</ball1></ball>
<cat><cat1>C</cat1></cat>
<dog><dog1>D</dog1></dog>
<ele><ele1>E</ele1></ele>
</root>
I don't know about the specifics of the parser you are using, but this is an intrinsic XML issue.
You can use below sample code.
resultArray = [[NSMutableArray alloc] init];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:webData];
[parser setDelegate:self];
[parser parse];
delegate methods to parse XML data
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSLog(#"error occured %#",parseError);
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(#"Did Start Document");
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
self.currentElement = elementName;
if([elementName isEqualToString:#"root"] && !itemDictionary){
self.itemDictionary = [[NSMutableDictionary alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[itemDictionary setObject:string forKey:currentElement];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"root"] && itemDictionary)){
[resultArray addObject:itemDictionary];
currentItem = nil;
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog("After parsing : %#", resultArray);
}
itemDictionary is a NSMutableDictionary.
I have edited my previous answer. (currentItem is itemDictionary).
In this sample code, itemDictionary is to store all values with key (when we parsing the data).
itemDictionary - {
apple1 = A
ball1 = B
cat1 = C
dog1 = D
ele1 = E
}
//--------------------------
<?xml version="1.0"?>
<root>
<apple id='10'><apple1>A</apple1></apple>
<ball><ball1>B</ball1></ball>
<cat><cat1>C</cat1></cat>
<dog><dog1>D</dog1></dog>
<ele><ele1>E</ele1></ele>
<root>
In didStartElement method, you have to use below sample code.
if([elementName isEqualToString:#"apple"]){
NSString *attributeValue = [attributeDict objectForKey:#"id"];
NSLog("Attribute value : %#", attributeValue);
}
I hope, it will help you.

How to limit the xml parsing in iphone

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.

Parsing XML for iPhone (aMule downloads/ search results)

I am currently working on a software to control aMule status of my server through the iPhone,
i created a socket that spits out xml which should be parsed out, but because NSXMLParser is event-drive, i'm having problems in understanding how this could work...
I thought of this type of XML structure, if you have ideas of a better way to structure it please tell me!! :D
<root type="donwloads"> <-- specifies downloads or search results
<file name="Ubuntu_9_10.iso" status="[11,6%]" />
<file name="Fedora 12.iso" status="[56,2%]" />
</root>
What i was thinking is, as i want to put this in a tableview, most probably i will need a NSMutableArray with lots of NSDictionaries based on the results, every dict should be a file.. what do you guys propose?? how should i handle this situation?
Thanks
Write a parser class that turns nodes into Core Data managed objects and saves them to the managed object context, when a parser callback event is fired.
Use an NSFetchedResultsController to access the Core Data store. As the managed objects come in and are saved, the results controller updates the table view with whatever results it fetches.
An NSMutableArray of NSDictionary seems like a reasonable approach for your in-memory data structure.
You'll basically have a series of callbacks that build up that array as NSXMLParser runs through your XML file:
- (void) parseXML:(NSString *) filename {
NSURL *xmlURL = [NSURL fileURLWithPath:filename];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[xmlParser setDelegate:self];
[xmlParser parse];
// Check for errors.
NSError *errorCode = [xmlParser parserError];
if (errorCode) {
// handle error here
NSLog(#"%#", [errorCode localizedDescription]);
}
[xmlParser release];
}
And your main delegate:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
// If certain elements are found initialize the object
if ([elementName isEqualToString:"#file"]) {
NSMutableDictionary *currentFile = [[NSMutableDictionary alloc] init];
// Look through the attributes add stuff to your dictionary
// Add it to your array.
}
}
Since all of your data is returned in attributes you can do it this way. Otherwise you'd need to store the file and build it up (the foundCharacters delegate) finally adding it to your array when the file's tag occurs in the didEndElement delegate.
Thanks a lot for your answers :D fortunately i resolved the problem 10 minutes after :D
ill post what i did:
XML:
<root>
<downloads>
<file type="text" name="fdsdf" />
<file type="text" name="sdfsdfssds" />
</downloads>
</root>
NSXMLParser delegates:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if([elementName isEqualToString:#"downloads"] || [elementName isEqualToString:#"results"]){
NSLog(#"starting or downloads or results");
if(xmlArray){
xmlArray= nil;
}
self.xmlArray= [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:#"file"]){
NSLog(#"found file...");
[self.xmlArray addObject:attributeDict];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if([elementName isEqualToString:#"downloads"] || [elementName isEqualToString:#"results"]){
if([elementName isEqualToString:#"downloads"]){
NSLog(#"downloads found: %#... reloading table", xmlArray);
}
}
}
I hope this can possibly help someone which has my same problem :D

to extract a part of the URl after XML parsing?

I am trying to parse an XML file in which an element named "description" is as given below:
<description>
<![CDATA[
<a href='http://www.okmagazine.com/posts/view/13756/'>
<img src='http://www.okmagazine.com/img/photos/thumbs/27044' />
</a>
<br />
Ashlee and Pete take their tiny tot to FAO Schwarz in NYC for some new toys.
<p> <strong>Pete Wentz</strong> and <strong>Ashlee Simpson Wentz</strong> made the new parent pilgrimage to New York’s FAO Schwarz today, where 6-month old <strong>Bronx Mowgli </strong>was the...]]>
</description>
What I want is to get the link in the tag <img src='http://www.okmagazine.com/img/photos/thumbs/27044'> using which I can display an image in my image view... How can I separate this string from the contents of description tag?
A part of code when parsing is as given below
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(#"found characters: %#", string);
// save the characters for the current item...
if ([currentElement isEqualToString:#"title"]) {
[currentTitle appendString:string];
} else if ([currentElement isEqualToString:#"link"]) {
[currentLink appendString:string];
} else if ([currentElement isEqualToString:#"description"]) {
[currentSummary appendString:string];
} else if ([currentElement isEqualToString:#"pubDate"]) {
[currentDate appendString:string];
}
}
Please help
regards
Arun
I've never used that exact framework, but what you have to keep in mind is that while it will notify you when it finds the CDATA, anything inside is just plain-text to the parser. So it looks like you want to implement foundCDATA. You'll get passed a NSData block, and from there you have to parse the contents. Now, you can use another parser to do that, but it's probably faster just to do manual substring.
Have you thought about using regexp?
NSString *str = #"<![CDATA[<a href='http://www.okmagazine.com/posts/view/13756/'><img src='http://www.okmagazine.com/img/photos/thumbs/27044' /></a><br />Ashlee and Pete take their tiny tot to FAO Schwarz in NYC for some new toys. <p> <strong>Pete Wentz</strong> and <strong>Ashlee Simpson Wentz</strong> made the new parent pilgrimage to New York’s FAO Schwarz today, where 6-month old <strong>Bronx Mowgli </strong>was the...]]>";
NSRange range = [str rangeOfString: #"<img src='"];
str = [str substringFromIndex: range.location + range.length];
range = [str rangeOfString: #"'"];
str =[str substringToIndex: range.location];
CFShow(str);
Attributes are passed in to the didStartElement delegate method of the parser as a dictionary of strings keyed by attribute name. Thus, you can extract the urls you want from the attributes using NSDictionary's objectForKey: with the attribute name as the key. i.e.:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName compare: #"img"] == NSOrderedSame) // check for <img ...> element
{
NSString* url = [attributeDictionary objectForKey:#"src"];
// url now contains the url you require from the HTML