没有得到预期的字符串的NSXMLParser解析
我解析它像标签之间有数据的XML经过“S |nºconta|” .I'm保存此如下没有得到预期的字符串的NSXMLParser解析
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
foundText = (NSMutableString *)[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
哪里foundText
是NSMutableString
。但是我没有把完整的数据作为“S |nºconta|”相反,我只是“nºconta|”其中“S |”字符被删除。
凡在XML <Details>S |nºconta|</Details>
在猜测你在XML非法字符 - 常规ASCII范围(0-127)以外的任何东西应该使用& #XX进行转义;或一个等效的命名实体。
对不起,我不明白...我该怎么办? – user3162102
你应该确认你的文档真的是UTF-8编码,而不仅仅是声称。 –
你知道吗,找到的字符:可能会被多次调用一个元素不是吗? Apple并不保证只给你一小段文字。 解析器对象可能会向委托人发送几个解析器:foundCharacters:消息以报告元素的字符。由于字符串可能只是当前元素的总字符内容的一部分,因此您应该将其附加到当前字符累积,直到元素更改。 –
据我所见,它工作得很好。
@implementation XMLDELEGATE
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
NSLog(@"didStartElement(%@)",elementName);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(@"didEndElement(%@)",elementName);
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"foundCharacters(%@)",string);
}
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
static const unsigned char bytes[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Details>S |nºconta|</Details>";
NSXMLParser *p;
NSData *d = [NSData dataWithBytes:bytes length:sizeof(bytes)-1];
p = [[NSXMLParser alloc] initWithData:d];
NSLog(@"data=%@",d);
p.delegate = [XMLDELEGATE new];
[p parse];
}
@end
输出这样的:
2014-03-01 15:35:07.272 xmlp2[35923:303] data=<3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 3d225554 462d3822 3f3e3c44 65746169 6c733e53 207c6ec2 ba636f6e 74617c3c 2f446574 61696c73 3e>
2014-03-01 15:35:07.273 xmlp2[35923:303] didStartElement(Details)
2014-03-01 15:35:07.273 xmlp2[35923:303] foundCharacters(S |n)
2014-03-01 15:35:07.273 xmlp2[35923:303] foundCharacters(ºconta|)
2014-03-01 15:35:07.273 xmlp2[35923:303] didEndElement(Details)
正如我在对方的回答说,你可能不重视的多次调用foundCharacters。作为代表,您有责任将多个字符串数据块粘贴在每个元素中(如果发生这种情况,则为!CDATA)
[未从xml解析中获取正确的字符串](http:// stackoverflow。 com/questions/21950788/not-getting-proper-string-from-xml-parsing) – CRD