How to Post String with Special Character and Thai Language Using Xml Parsing in Objective C

How to post string with special character and Thai Language using XML parsing in Objective C?

You can replace your string so that it will allow you to send special character. You can use string method stringByReplacingOccurrencesOfString

 NSString *RaisedBy="Your Special character string";
RaisedBy = [RaisedBy stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
RaisedBy = [RaisedBy stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
RaisedBy = [RaisedBy stringByReplacingOccurrencesOfString:@">" withString:@">"];
RaisedBy = [RaisedBy stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
RaisedBy = [RaisedBy stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

This code will also support thai language.

How Can I parse Special characters in XML by obj-c?

Try while you creating XML use CDATA tags like

<![CDATA[Transport information Classic World's]]>

Also here is a list of HTML Tags and more cases XML with those characters is invalid, unless they are contained within a CDATA.
Also try this Question hope with help you

As You asking the you can not change the XML so till now you will not resolve i think parser is not able to parse this XML.

Parsing xml in NSXMLParser

For implementing NSXMLParser you need to implement delegate method of it.

First of all initiate NSXMLParser in this manner.

- (void)viewDidLoad {

[super viewDidLoad];

rssOutputData = [[NSMutableArray alloc]init];

//declare the object of allocated variable
NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@""]];// URL that given to parse.

//allocate memory for parser as well as
xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
[xmlParserObject setDelegate:self];

//asking the xmlparser object to beggin with its parsing
[xmlParserObject parse];

//releasing the object of NSData as a part of memory management
[xmlData release];

}
//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if( [elementName isEqualToString:@"question"])
{

strquestion = [[NSMutableString alloc] init];

}
}


//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
// init the ad hoc string with the value
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
// append value to the ad hoc string
[currentElementValue appendString:string];
}
NSLog(@"Processing value for : %@", string);
}


//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if( [elementName isEqualToString:@"question"])
{
[strquestion setString:elementName];
}

[currentElementValue release];
currentElementValue = nil;
}

The above delegate method is sent by a parser object to its delegate when it encounters an end of specific element. In this method didEndElement you will get value of question.

How to handle the CDATA tag while parsing an XML file in iPad

If you need to extract the string from CDATA, you could use this block in foundCDATA:

NSMutableString *lStr = [[NSMutableString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];

Xml to dictionary parsing using XML reader

if you are newbie and don't know how to parse xml to dictionary... try with the below methods...

in .h file add this methods

#import 


@interface XMLReader : NSObject
{
NSMutableArray *dictionaryStack;
NSMutableString *textInProgress;
NSError **errorPointer;
}

+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer;
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer;

@end

and in your .m file parse your URL using these methods.

NSString *const kXMLReaderTextNodeKey = @"text";

@interface XMLReader (Internal)

- (id)initWithError:(NSError **)error;
- (NSDictionary *)objectWithData:(NSData *)data;

@end


@implementation XMLReader

#pragma mark -
#pragma mark Public methods

+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)error
{
XMLReader *reader = [[XMLReader alloc] initWithError:error];
NSDictionary *rootDictionary = [reader objectWithData:data];
[reader release];
return rootDictionary;
}

+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return [XMLReader dictionaryForXMLData:data error:error];
}

#pragma mark -
#pragma mark Parsing

- (id)initWithError:(NSError **)error
{
if (self = [super init])
{
errorPointer = error;
}
return self;
}

- (void)dealloc
{
[dictionaryStack release];
[textInProgress release];
[super dealloc];
}

- (NSDictionary *)objectWithData:(NSData *)data
{
// Clear out any old data
[dictionaryStack release];
[textInProgress release];

dictionaryStack = [[NSMutableArray alloc] init];
textInProgress = [[NSMutableString alloc] init];

// Initialize the stack with a fresh dictionary
[dictionaryStack addObject:[NSMutableDictionary dictionary]];

// Parse the XML
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
BOOL success = [parser parse];

// Return the stack's root dictionary on success
if (success)
{
NSDictionary *resultDict = [dictionaryStack objectAtIndex:0];
return resultDict;
}

return nil;
}

#pragma mark -
#pragma mark NSXMLParserDelegate methods

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// Get the dictionary for the current level in the stack
NSMutableDictionary *parentDict = [dictionaryStack lastObject];

// Create the child dictionary for the new element, and initilaize it with the attributes
NSMutableDictionary *childDict = [NSMutableDictionary dictionary];
[childDict addEntriesFromDictionary:attributeDict];

// If there's already an item for this key, it means we need to create an array
id existingValue = [parentDict objectForKey:elementName];
if (existingValue)
{
NSMutableArray *array = nil;
if ([existingValue isKindOfClass:[NSMutableArray class]])
{
// The array exists, so use it
array = (NSMutableArray *) existingValue;
}
else
{
// Create an array if it doesn't exist
array = [NSMutableArray array];
[array addObject:existingValue];

// Replace the child dictionary with an array of children dictionaries
[parentDict setObject:array forKey:elementName];
}

// Add the new child dictionary to the array
[array addObject:childDict];
}
else
{
// No existing value, so update the dictionary
[parentDict setObject:childDict forKey:elementName];
}

// Update the stack
[dictionaryStack addObject:childDict];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
// Update the parent dict with text info
NSMutableDictionary *dictInProgress = [dictionaryStack lastObject];

// Set the text property
if ([textInProgress length] > 0)
{
[dictInProgress setObject:textInProgress forKey:kXMLReaderTextNodeKey];

// Reset the text
[textInProgress release];
textInProgress = [[NSMutableString alloc] init];
}

// Pop the current dict
[dictionaryStack removeLastObject];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
// Build the text value
[textInProgress appendString:string];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
// Set the error pointer to the parser's error object
*errorPointer = parseError;
}

@end

I think this would be helpful to you for parsing the xml data.

Using NSXMLParser with CDATA

The point of CDATA is that anything within it is not treated as part of the XML document.
So if you have tags in CDATA the parser will ignore them.

I'm guessing this CDATA is in the description element. So you'll need to extract the tags from the "description" element, either manually or via another instance of a parser.

objective c XMLWriter

Try this:

[xmlWriter writeCharacters:[NSString stringWithFormat:@"request: %@ can go in here", testString]]; //this line here

Chinese Character Encoding Issue ios

I just searched it and found one of the useful Answer from here.

It's natural that Chinese and Japanese characters don't work with ASCII string encoding. If you try to escape the string by Apple's methods, which you definitely should to avoid code duplication, store the result as a Unicode string. Use one of the following encodings:

NSUTF8StringEncoding
NSUTF16StringEncoding
NSShiftJISStringEncoding (not Unicode, Japanese-specific)

UPDATE

For Example you can encode Decode your chinese String like below:

NSString * test = @"汉字马拉松是";
NSString* encodedString =[test stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSLog(@"====%@",encodedString);

OUTPUT IS:

%E6%B1%89%E5%AD%97%E9%A9%AC%E6%8B%89%E6%9D%BE%E6%98%AF

Then Decode it like:

NSString* originalString =[encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"====%@",originalString);

OUTPUT IS:

汉字马拉松是

Getting Junk and special character while decoding string

Go this way

  1. download Base64 files from here

  2. Pull out these two files (NSData+Base64.h, NSData+Base64.m)from downloaded folder and add to your project.

  3. disable ARC for these newly added files (if you enable ARC in your project)

  4. #import "NSData+Base64.h" into your file

  5. use below two methods to acomplish your task

    base64Encode

    base64Decode

Here is the my code snip, how I did in my demo example

#import "ViewController.h"
#import "NSData+Base64.h"

@interface ViewController ()
@end

@implementation ViewController

@synthesize messageTextField;
@synthesize resultBase64Label;
@synthesize resultPlainTextLabel;

- (void)viewDidLoad
{
[super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

- (IBAction)convertToBase64:(id)sender {

//keypad go back
[messageTextField resignFirstResponder];

NSString *resultBase64String = [self base64Encode:messageTextField.text];
resultBase64Label.text = resultBase64String;
}

- (IBAction)convertToPlainText:(id)sender {

NSString *resultPlainString = [self base64Decode:resultBase64Label.text];
resultPlainTextLabel.text = resultPlainString;
}

//convert plain text o base64
- (NSString *)base64Encode:(NSString *)plainText
{
NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainTextData base64EncodedString];
return base64String;
}

//convert base64 to plain text
- (NSString *)base64Decode:(NSString *)base64String
{
NSData *plainTextData = [NSData dataFromBase64String:base64String];
NSString *plainText = [[NSString alloc] initWithData:plainTextData encoding:NSUTF8StringEncoding];
return plainText;
}

@end

and here is the result screen

Sample Image



Related Topics



Leave a reply



Submit