2016-08-11 79 views
0

我想解析XML数据。我没有使用XMLParser。我用下面的代码,它以某种方式工作。我将XML解析为JSON,并以字典格式获得响应。下面是我的代码 -解析XML数据目标c

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

     NSError *jsonError; 

    if (error == nil){ 

    NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError]; 

    if (jsonError) { 

    NSLog(@"Error : %@",error); 

    failureBlock(@{@"ErrorCode": [NSString stringWithFormat: @"%ld", (long)jsonError.code], 

    @"ErrorText": jsonError.localizedDescription}); 

    } else { 

    NSLog(@"success : %@",jsonResponse); 

    successBlock(jsonResponse); 

    } 

    }else{ 

    failureBlock(@{@"ErrorCode": [NSString stringWithFormat: @"%ld", (long)error.code], 

    @"ErrorText": error.localizedDescription}); 

    } 

    }] resume]; 

虽然这是工作,但突然间,我开始收到错误消息像 -

ErrorCode = 3840; 
    ErrorText = "The data couldn\U2019t be read because it isn\U2019t in the correct format."; 

那么它是如何工作的前面?有人可以请指导我如何编写正确的XML解析。如果首先重定向到上面的代码中绕过的登录页面,并且我们直接获取XML响应,也是xml url。在应用程序中,我们拥有用于登录的UIWebView容器,并且我们可以在每次服务调用时获取这些Cookie。在上面的代码中,它在工作时绕过登录页面并以json格式返回响应。我也试过以下代码 -

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

     NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithData:data]; 

     [xmlparser setDelegate:self]; 

     [xmlparser parse]; 


    }] resume]; 

然后写了didStartElement,foundCharacters和didEndElement。但它试图解析登录页面本身。如果我使用NSXMLParser,登录页面不会被绕过。

请帮忙,任何建议是最受欢迎的。

+0

转换为字符串格式'的NSString您回应*的myString = [[NSString的页头] initWithData: myData编码:NSUTF8StringEncoding]; ',NSLog日志生成的字符串,并检查它是否在正确的格式。 – Harsh

+0

使用http://jsonlint.com/用于JSON或http://www.xmlvalidation.com/用于验证XML响应是否正确。 – Harsh

+0

@Harsh是的,我确实打印了数据,看起来我的第一种方法并没有绕过登录页面。我改变了网址,它开始工作,但是第一种方法是解析XML的权利? –

回答

4

您也可以使用此链接形式的XML解析:https://github.com/nicklockwood/XMLDictionary

也试试这个代码:

NSString *baseUrl = [NSString stringWithFormat:@"your string"]; 


NSURL * url = [NSURL URLWithString:baseUrl]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 
[request setHTTPMethod:@"GET"]; 
[request setHTTPShouldHandleCookies:NO]; 

[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
    if (error) { 
     failure(error); 
    } else if(response) 
    { 
     NSDictionary * jsonDic =[NSDictionary dictionaryWithXMLData:data]; 
     NSLog(@"Response print Hear%@",jsonDic); 

    } 
}];