Reputation: 1202
I am trying to parse some XML data and append the parsed data into an NSString object. I have successfully parsed the XML data using NSXMLParser, but when I log the value of the string called arrayString
, I just get the value of the first <name>
, instead of all of them. What am I doing wrong?
Here is my code:
(void)parseWithData:(NSData *)data {
parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:self];
//You might want to consider additional params like:
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
//And then finally (which activates the delegates):
[parser parse];
NSLog(@"The content of the array is%@",childElement);
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = nil;
currentElement = [elementName copy];
if ([elementName isEqualToString:@"row"]) {
//This means the parser has entered the XML parent element named: xmlParentElement
//All of the child elements that need to be stored in the array should have their own IVARs and declarations.
childElement = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//For all child elements, run this if statement.
if ([currentElement isEqualToString:@"name"]) {
[childElement appendString:string];
NSLog(string);
[arrayString stringByAppendingString:string];
// NSLog(arrayString);
}
And I parse the data by calling these methods:
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
[self parseWithData:data];
Upvotes: 2
Views: 375
Reputation: 53860
The stringByAppendingString
function returns a NSString
. It doesn't alter the receiver.
You need to fix your use of stringByAppendingString
. For example, in foundCharacters
, replace this:
[arrayString stringByAppendingString:string];
With this:
arrayString = [arrayString stringByAppendingString:string];
Apple's documentation on stringByAppendingString
:
stringByAppendingString:
Returns a new string made by appending a given string to the receiver.
Also, when appending strings, don't forget to initialize the string before you append to it.
Upvotes: 1
Reputation: 134
I think the stringByAppendingString method creates a new NSString. Try this instead of that:
arrayString = [arrayString stringByAppendingString:string];
Upvotes: 1