问题
I'm trying to get values from server by parsing the xml data returned through the websevice.
the code used for parsing is below
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
rValue= @"";
isTag = FALSE;
if ([elementName caseInsensitiveCompare:@"BusinessName"] == NSOrderedSame)
isTag=YES;
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)strin{
if (isTag) {
rValue =strin;
}
}
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName caseInsensitiveCompare:@"BusinessName"] == NSOrderedSame)
[myarray addObject:rValue];
}
-(void) parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"%@",myarray);
}
rValue
is a static string;
After printing my array, it looks like this,
(
"Book Store",
"Birch river grill",
PIC,
"Drink Juice",
"Cofee Cafee",
"Diag Block",
"Delici Store",
"\n\n",
"Spoon Fork",
"\n",
"\n\n",
"\n\n\n",
Allow,
"Enjoy Traveling",
"Grwing Three",
"\n",
"\n\n"
)
Why the \n(backslashes) are occuring instead of values(BusinessName)?, I checked the webservice in the browser, the values are returning correctly. Totally there are 17 elements returning and you can see some of the strings printed in log without double qoutes. It's not an issue. But, why is that appearing like that. How can I get the correct values instead of backslashes.
- What am I doing wrong?
- How to solve this?
回答1:
Since foundCharacters
can be called multiple times per content of a tag, this is incorrect:
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)strin{
if (isTag) {
rValue =strin;
}
}
Rather than assigning strin
to rValue
, you should be appending it. Currently, the actual value (say, @"BusinessName"
) gets recognized and assigned, but then the @"\n\n\n"
continuation string comes along inside the same tag, and gets assigned on top of the value that has been found first.
Make rValue
an NSMutableString
, and use appendString
, like this:
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)strin{
if (isTag) {
[rValue appendString:strin];
}
}
Note that the content wold have \n
s at the end as well. If you do not need these trailing characters, you would need to remove them manually, for example, by calling stringByTrimmingCharactersInSet:
, and passing it [NSCharacterSet whitespaceAndNewlineCharacterSet]
as the parameter:
NSString *finalValue = [rValue stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]
];
来源:https://stackoverflow.com/questions/19703039/n-appearing-instead-of-string-while-getting-values-from-xml-service