前言
目前主流网络数据格式:json 和 XML 这两种格式,这里主要介绍一下 XML 格式网络数据解析。
XMl 数据测试接口:
https://blog.devhitao.com/sitemap.xml
hhttps://rss.sina.com.cn/sina_all_opml.xml
XML 数据网络请求时,响应可能有必要添加 application/xml
字段,eg: [NSSet setWithObjects:@"application/xml", nil];
如有需要,可能需要添加 libxml2
系统类库。
XML 格式
属性
标签
XPath
在 XPath 中,有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点。XML 文档是被作为节点树来对待的。树的根被称为文档节点或者根节点。
1 2 3 4 5 6 7 8
| NSError * err; ONOXMLDocument * xmlDoc = [ONOXMLDocument HTMLDocumentWithData:responseObject error:&err]; [xmlDoc enumerateElementsWithXPath:@"//url" usingBlock:^(ONOXMLElement * _Nonnull element, NSUInteger idx, BOOL * _Nonnull stop) { if (element) { NSLog(@"%@", [[element firstChildWithXPath:@".//loc"] stringValue]); NSLog(@"%@", [[element firstChildWithXPath:@".//lastmod"] stringValue]); } }];
|
XPath 类似语法
1 2 3 4
| //li[@class='video matrix' .//a//div[@class='img']//img//@src .//a//@href .//a//@title
|
XML 请求
需求:
POST 请求,body 为 xml 格式数据。
分析:
借助 XMLDictionary
将字典转化为 xml 字符串,进行拼接,然后使用原生请求方进行请求。返回 xml data 数据,将其 字典 化。
网上还要其他方法,可以自行研究。
以下是部分请求代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| NSMutableURLRequest *request; NSURL * requestUrl; NSString * prefixUrl = @"https://xxx.com/xxx/api"; NSDictionary * bodyParameters = @{@"userName":@"devhitao", @"usePwd":@"guogong"}; requestUrl = [NSURL URLWithString:prefixUrl]; request = [[NSMutableURLRequest alloc] initWithURL:requestUrl]; //body NSString * XMLBody = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?><body>%@</body>", bodyParameters.innerXML]; NSData * bodyData = [XMLBody dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:bodyData]; /* 根据要求设置请求头 head eg: */ [request setValue:@"*/*" forHTTPHeaderField:@"Accept"]; [request setValue:@"text/html; charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; [request setHTTPMethod:@"POST"]; NSURLSession * urlSession = [NSURLSession sharedSession]; NSURLSessionDataTask * dataTask = [urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSHTTPURLResponse * httpUrlResponse = (NSHTTPURLResponse *)response; if (data) { NSDictionary * dict = [NSDictionary dictionaryWithXMLData:data];//xml data格式字典化 }else{ } }]; [dataTask resume];
|
第三方库
参考资料
文档信息