Decode percent escaped string inside NSXMLParser delegate method - objective-c

i'm getting a UTF8 encoded data from a server data is like Less%20than%20100 but i need this data in Less than 100 (decoded format),my NSXMLParsing delegate method is like
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:#"option"]) {
dict = [[NSMutableDictionary alloc]init];
[dict setValue:[attributeDict objectForKey:#"text"] forKey:#"text"];/* Here itself i need to decode & save in to my dict */
}
How to decode this data.

After you have decoded your xml, use stringByReplacingPercentEscapesUsingEncoding: method on NSString :
NSString *decoded = [text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
See the docs here.

Related

Parsing xml to objective-c

i'm trying to parse an xml document into 2 NSMutableArrays, but it seems like it is overwriting my array. my xml doc contain 3 objects, but my array only contain 1. Why does it overwrite the previous added objects from the xml doc?
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:#"playlist"]) {
title = [attributeDict valueForKey:#"title"];
listid = [[attributeDict valueForKey:#"id"] intValue];
lists = [[NSMutableArray alloc]init];
lists2 = [[NSMutableArray alloc]init];
[lists addObject:title];
[lists2 addObject:[NSString stringWithFormat:#"%d", listid]];
}
NSLog(#"%d", lists.count);
}
xml doc:
<?xml version="1.0"?>
<Lists>
<playlist title="Quo Vadis" id="0"/>
<playlist title="Lord of the Rings" id="1"/>
<playlist title="Face" id="2"/>
</Lists>
You assign a new (empty) array to lists and lists2 each time in didStartElement,
and therefore overwrite what was previously in those variables.
The arrays must be created only once, before you start the parse method.

How to strip the string to get the URL in the HTML <img>?

I am writing a RSS project on iPhone. I wonder how I can strip everything inside this tag just to get the image URL:
<description><![CDATA[ <img src="http://vnexpress.net/Files/Subject/3b/bd/67/91/Lat-xe-xang-2.jpg">Trưa 7/5, chiếc xe bồn chở 25.000 lít xăng từ Hà Tĩnh vào Quảng Bình bị lật nghiêng trên quốc lộ 1A khiến xăng chảy lênh láng ra đường. ]]></description>
I just want to get the string
http://vnexpress.net/Files/Subject/3b/bd/67/91/Lat-xe-xang-2.jpg
Please show me how to do it in this case?
I recommend NSXMLParser.
See here: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html
use this method...
- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
NSString *someString = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
}
hoping this helps..
Edit:
Oh, #Ankit Srivastava answer is right. I didn't catch that is a CDATA block. Follow his answer, but I don't delete mine, couse this still can be useful to you.
You should implement NSXMLParser delegate. In your .h file <NSXMLParserDelegate>
And then you have to put 3 useful method in your m file.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (element == nil) // where element is a NSMutableString
element = [[NSMutableString alloc] init];
[element appendString:string];
}
That doesn't matte rif you have or it will always call didStart end didEnd.
Now we have ex: :
elementName //contains your tag name. In this case "mytag"
element // contains text beetween tags. In this case null. But in <mytag>something</mytag> element = something.
attributeDict //This is probably most important to you. That contains NSDictionary with all your parameters. In above example this is a dictionary with key: myparam and object: test

NSXMLParser to create nodes and NSMutableArray

i'm looking for a advise. I want to parse an XML file with NSXMLParser, and i wonder what i should do with tags and parameters.
Fo example i have:
<template>
<template name="default" layout="absolute">
<image tmpl="topbanner"/>
<list tmpl="list">
<font tmpl="listfont"/>
<item target="target1">
<text>Target1</text>
</item>
<item target="target2">
<text>Target2</text>
</item>
<item target="target3">
<text>Target3</text>
</item>
.
.
.
And later i want to create an objects base on this information. So - where should i store retrieve information from parser? In method:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
element = [NSMutableString string];
}
I see that i can simply recieve atributes ang tags, but should I in this point write it in NSMutableArray or NSDictionary?
I've read NSXMLParser how to pass the NSMutableDictionary to a NSMutableArray But is it the best way?
If you know that a <list> element contains an array of subelements, you'll probably want to create an array or dictionary at the start of that block:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"list"]) {
self.list = [NSMutableDictionary dictionary];
self.listName = [attributeDict objectForKey:#"tmpl"]
}
else if ([elementName isEqualToString:#"item"]) {
self.itemKey = [attributeDict objectForKey:#"target"];
}
else if ([elementName isEqualToString:#"text"]) {
self.data = [NSMutableString string];
}
else if ([elementName isEqualToString:#"font"]) {
self.font = [attributeDict objectForKey:#"tmpl"];
}
}
Then you can add the simple <item> elements in your -parser:didEndElement:... method:
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if (elementName isEqualToString:#"text") {
// no action needed here -- data already contains the text
}
else if (elementName isEqualToString:#"item"]) {
[self.list setObject:[self.data copy] forKey:self.itemKey;
self.itemKey = nil;
}
else if ([elementName isEqualToString:#"list"]) {
// do something appropriate with the list
[self.template setObject:self.items forKey:self.listName];
self.listName = nil;
self.list = nil;
}
}
This all presumes that you've got properties for font, data, itemKey, and so on... basically whatever you need to remember all the state you need until you can create the related object. Once you have the data you need, usually in the didEnd method, create the object, store it somewhere, and clear out the saved data.
This isn't the only approach to parsing the data. For example, you might want to go with a stack-based approach instead. But the idea illustrated above is probably the easiest to understand, and if the data isn't too complicated it's not hard to manage.
To get what's inside the tag use:
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[element appendString:string];
}
Then check in :
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
To get the attributes :
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"image"]) {
NSString *imageName = [attributeDict objectForKey:#"tmpl"];
}
}

XML parsing in IOS Shows NULL value in label?

i m doing XML parsing using NSXMLParserDelegate..I m getting null value when i print the value in label...I m using simple xml file got in an internet.You can check what is in that file too.anyone pls help..Here is my code
#import "xmlViewController.h"
#implementation xmlViewController
#synthesize label;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.bonifacedesigns.com/tuts/xmltest.xml"]];
receivedData=[[NSMutableData alloc]initWithContentsOfURL:url];
dataParser=[[NSXMLParser alloc]initWithData:receivedData];
dataParser.delegate=self;
[dataParser parse];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
// if(!xmlString){
//
// }else
// {
// [xmlString setString:#""];
// }
if([elementName isEqualToString:#"elements"])
{
xmlString=[NSMutableString alloc];
[xmlString setString:#""];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
xmlString= (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"element"]){
NSString *string=xmlString;
[xmlArray addObject:string];
label.text=[NSString stringWithFormat:#"%#",xmlArray];
}
}
#end
This is my XML file....I want to print XML Data Parsed! in my label.Help me with that.I have edited the code and check now
<elements>
<element myData="XML Data Parsed!"/>
</elements>
check this:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
// if(!xmlString){
//
// }else
// {
// [xmlString setString:#""];
// }
if([elementName isEqualToString:#"elements"])
{
xmlString=[[NSMutableString alloc]initWithCapacity:5];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
xmlString= (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"element"]){
[attributeDict objectForKey:#"myData"];
[xmlString setString:#""];
NSString *string=xmlString;
[xmlArray addObject:string];
label.text=[NSString stringWithFormat:#"%#",xmlArray];
}
I m getting error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with setString:'
*** First throw call stack:
(0x13ba052 0x154bd0a 0x1362a78 0x13629e9 0x1387970 0x2a26 0x9e1a35 0x5171532 0x9e002d 0x26b8 0xd764e 0x37a73 0x37ce2 0x37ea8 0x3ed9a 0xfbe6 0x108a6 0x1f743 0x201f8 0x13aa9 0x12a4fa9 0x138e1c5 0x12f3022 0x12f190a 0x12f0db4 0x12f0ccb 0x102a7 0x11a9b 0x2238 0x2195 0x1)
terminate called throwing an exception
It seems you have several errors in your code.
The mutable string xmlString isn't properly initialized, on the line :
xmlString = [NSMutableString alloc]; // wrong
This should look like : xmlString = [[NSMutableString alloc] initWithCapacity:X];.
Also, when the parser finds characters, you replace the entire existing mutable string, instead of appending them to the existing content, or try to because according to the code, you simply make a memory address compare and waste the result (==).
// wrong
xmlString == (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
This should look like :
[xmlString appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
Finally in didEndElement, I'm not sure what you are trying to achieve, but you add the string object reference to an array, and then set the label text to display the content of the array... as long as the mutable array is well allocated and initialized (what I'm really not sure), the label should display at least the array content. But you might consider to "flush" the mutable string ([xmlString setString:#""];) and not allocate it on every element.
EDIT :
The attributeDict maps attribute names as the keys with their values. I guess your attribute value can be accessed via [attributeDict objectForKey:#"myData"];.
I guess that the problem is in this line:
xmlString== (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Change == to =
Hope that explanation isn't needed.

NSMutableString issue with NSXMLParser

I am having a heck of a time with this -- I am trying to parse an XML file and set the text in a NSMutableString variable in order to later fill in a label's text as you can see below.
In my .h I have the following (simplified);
NSMutableString *contentsOfCurrentXMLProperty;
#property (nonatomic,retain) NSMutableString *contentsOfCurrentXMLProperty;
In my .m:
-(void) parseData {
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:myData];
[parser setDelegate:self];
[parser parse];
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"Title"]) {
NSLog(#"FOUND TITLE!");
contentsOfCurrentXMLProperty = [NSMutableString setString:#""];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"TITLE"]) {
myLabel.text = [contentsOfCurrentXMLProperty stringByReplacingOccurrencesOfString:#"[br]" withString:#"\n"];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[self.contentsOfCurrentXMLProperty appendString:string];
}
When I run my app, the data is downloaded and parsed correctly. I run into issues when my observer fires off the event again. The parseData method is called and I get an error that I have traced to the line that reads: "contentsOfCurrentXMLProperty = [NSMutableString setString:#""];
"
What is the proper way to create or init a NSMutableString variable for me to use over and over? When/Where is the best place to release it? How do I essentially clear the variable so that when the observer fires off the parseData method it will again be able to set "contentsOfCurrentXMLProperty"?
-setString: is an instance method, not a class method. If you already have a valid NSMutableString object assigned to contentsOfCurrentXMLProperty and simply want to clear it, then:
contentsOfCurrentXMLProperty = [NSMutableString setString:#""];
should be
[contentsOfCurrentXMLProperty setString:#""];
On the other hand, if you want to assign a new object to contentsOfCurrentXMLProperty, here's one valid way to do it:
self.contentsOfCurrentXMLProperty = [NSMutableString stringWithCapacity:0];