NSXML Parser在&之后跳过剩余的字符串在字符串中

时间:2014-06-02 12:22:10

标签: ios objective-c parsing nsxmlparser

我正在努力从服务器下载和解析数据。

avery的事情很好,但我发现它并没有像现在这样完全接受一些字符串,

搜索六小时后:(我无法找到问题。

我必须解析包含& 符号的字符串。在后端(服务器)我只需将其更改为& amp; ,以便NSXML Parser可以毫无问题地解析它。

示例字符串

Hello this is & my test string.

发生的一切是,

我刚刚开始

Hello this is

休息字符串正在跳过。

这是我的代码

message = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    "<XMLBody>"
    "<Head>"
    "<Document>"
    "<DocType>Query</DocType>"
    "<DocDate>%@</DocDate>"
    "</Document>"
    "<UserName>####</UserName>"
    "<Password>####</Password>"
    "<Database>%@</Database>"
    "</Head>"
    "<Body>"
    "<Query>%@</Query>"
    "</Body>"
    "</XMLBody>",currentDate,myDBName,myQuery];
uRL = [NSURL URLWithString:@"http://www.myserverpath"];
request = [NSMutableURLRequest requestWithURL:uRL];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
errorMsg = nil;
if (true)   
{
NSLog(@"Connection Build and waitng for response");
    xmldata = [ NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
errorParsing=NO;
NSString *data = [[NSString alloc] initWithData:xmldata encoding:NSASCIIStringEncoding];
    xmldata = [data dataUsingEncoding:NSUTF8StringEncoding];
    NSLog("Result is %@",data); // here every thing is just perfect.
xmlParser = [[NSXMLParser alloc] initWithData:xmldata];
[xmlParser setDelegate:self];
[xmlParser parse];
}
在上面的NSLog中,一切都很完美。

当我到达这里时

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[elementValue appendString:string];
    NSLog("String is = %@",string); // here i got half string

[string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
// convert again into & sign

// doing my other stuff.
}

在这个nslog中只获得了一半的字符串。

我该怎么做才能得到完整的字符串

Hello this is &amp; my test string.

1 个答案:

答案 0 :(得分:1)

这肯定会解决您的问题:)

我是从我的应用程序发布的。在服务器端,我只需用以下内容替换所有无效/特殊字符: -

从此链接http://en.wikipedia.org/wiki/Character_encodings_in_HTML

刚刚想出&amp; → & (ampersand, U+0026)所以我使用了一个使用数字26的技巧,其中%标记包含在parantheses中以编码这些敏感值。

& = [%26], > = [%3E], < = [%3C], ' = [%27], \ = [%22]   

使用您的URLRequest获取数据,并在此委托方法中再次替换这些字符

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{ 
    [elementValue appendString:string];
    string = [string stringByReplacingOccurrencesOfString:@"[%26]" withString:@"&"];
    string = [string stringByReplacingOccurrencesOfString:@"[%3E]" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"[%3C]" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"[%27]" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"[%22]" withString:@"\""];
}