【发布时间】:2017-04-12 03:58:01
【问题描述】:
我执行同步发布请求并获取 xml。现在我需要解析并将其保存在 NSDictionary 中。我尝试了许多来自网络的解决方案。但没有什么对我有用。这是我的代码:
//Response data object
NSData *returnData = [[NSData alloc]init];
NSString *param = @"{params}";
NSString *postString = [NSString stringWithFormat:@"request=%@",param];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"url"]];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
bool debug = YES;
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLFile:response];
if (debug && response) {
NSLog(@"Response >>>> %@", xmlDoc);
}
我用过这个xml reader。这是我在 nslog 中得到的结果:
2016-11-28 18:04:26.970 SyncPostReq[8667:305923] Response >>>> (null)
【问题讨论】:
-
dictionaryWithFile:不是您正在寻找的方法。它正在等待一个字符串路径!使用dictionaryWithData:=>NSDictionary *xmlDoc = [NSDictionary dictionaryWithData:response]; -
@Larme,谢谢,但没用。
-
哎呀(我之前的答案复制/粘贴错误),
NSDictionary *xmlDoc = [NSDictionary dictionaryWithData:returnData];(否则你应该至少有一个警告) -
@Larme,我得到它并将我的字符串转换为 nsdata,没用。
-
response真的是 XML 吗?可以分享一下吗?
标签: objective-c xml parsing post nsdictionary