#import <Foundation/Foundation.h> enum { XMLReaderOptionsProcessNamespaces = 1 << 0, // Specifies whether the receiver reports the namespace and the qualified name of an element. XMLReaderOptionsReportNamespacePrefixes = 1 << 1, // Specifies whether the receiver reports the scope of namespace declarations. XMLReaderOptionsResolveExternalEntities = 1 << 2, // Specifies whether the receiver reports declarations of external entities. }; typedef NSUInteger XMLReaderOptions; @interface XMLReader : NSObject <NSXMLParserDelegate> + (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer; + (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer; + (NSDictionary *)dictionaryForXMLData:(NSData *)data options:(XMLReaderOptions)options error:(NSError **)errorPointer; + (NSDictionary *)dictionaryForXMLString:(NSString *)string options:(XMLReaderOptions)options error:(NSError **)errorPointer; @end
#import "XMLReader.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "XMLReader requires ARC support." #endif NSString *const kXMLReaderTextNodeKey = @"text"; NSString *const kXMLReaderAttributePrefix = @"@"; @interface XMLReader () @property (nonatomic, strong) NSMutableArray *dictionaryStack; @property (nonatomic, strong) NSMutableString *textInProgress; @property (nonatomic, strong) NSError *errorPointer; @end @implementation XMLReader #pragma mark - Public methods + (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)error { XMLReader *reader = [[XMLReader alloc] initWithError:error]; NSDictionary *rootDictionary = [reader objectWithData:data options:0]; return rootDictionary; } + (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error { NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; return [XMLReader dictionaryForXMLData:data error:error]; } + (NSDictionary *)dictionaryForXMLData:(NSData *)data options:(XMLReaderOptions)options error:(NSError **)error { XMLReader *reader = [[XMLReader alloc] initWithError:error]; NSDictionary *rootDictionary = [reader objectWithData:data options:options]; return rootDictionary; } + (NSDictionary *)dictionaryForXMLString:(NSString *)string options:(XMLReaderOptions)options error:(NSError **)error { NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; return [XMLReader dictionaryForXMLData:data options:options error:error]; } #pragma mark - Parsing - (id)initWithError:(NSError **)error { self = [super init]; if (self) { self.errorPointer = *error; } return self; } - (NSDictionary *)objectWithData:(NSData *)data options:(XMLReaderOptions)options { // Clear out any old data self.dictionaryStack = [[NSMutableArray alloc] init]; self.textInProgress = [[NSMutableString alloc] init]; // Initialize the stack with a fresh dictionary [self.dictionaryStack addObject:[NSMutableDictionary dictionary]]; // Parse the XML NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; [parser setShouldProcessNamespaces:(options & XMLReaderOptionsProcessNamespaces)]; [parser setShouldReportNamespacePrefixes:(options & XMLReaderOptionsReportNamespacePrefixes)]; [parser setShouldResolveExternalEntities:(options & XMLReaderOptionsResolveExternalEntities)]; parser.delegate = self; BOOL success = [parser parse]; // Return the stack's root dictionary on success if (success) { NSDictionary *resultDict = [self.dictionaryStack objectAtIndex:0]; return resultDict; } return nil; } #pragma mark - NSXMLParserDelegate methods - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { NSLog(@"elementName___%@",elementName); NSLog(@"namespaceURI___%@",namespaceURI); NSLog(@"qName___%@",qName); NSLog(@"attributeDict___%@",attributeDict); // Get the dictionary for the current level in the stack NSMutableDictionary *parentDict = [self.dictionaryStack lastObject]; // Create the child dictionary for the new element, and initilaize it with the attributes属性 NSMutableDictionary *childDict = [NSMutableDictionary dictionary]; [childDict addEntriesFromDictionary:attributeDict]; // If there's already an item for this key, it means we need to create an array id existingValue = [parentDict objectForKey:elementName]; if (existingValue) { NSMutableArray *array = nil; if ([existingValue isKindOfClass:[NSMutableArray class]]) { // The array exists, so use it array = (NSMutableArray *) existingValue; } else { // Create an array if it doesn't exist array = [NSMutableArray array]; [array addObject:existingValue]; // Replace the child dictionary with an array of children dictionaries [parentDict setObject:array forKey:elementName]; } // Add the new child dictionary to the array [array addObject:childDict]; } else { // No existing value, so update the dictionary [parentDict setObject:childDict forKey:elementName]; } // Update the stack [self.dictionaryStack addObject:childDict]; } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { NSLog(@"elementName___%@",elementName); NSLog(@"namespaceURI___%@",namespaceURI); NSLog(@"qName___%@",qName); // Update the parent dict with text info NSMutableDictionary *dictInProgress = [self.dictionaryStack lastObject]; NSString *trimmedString = [self.textInProgress stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; // Set the text property if ([trimmedString length] > 0) { // trim after concatenating // NSString *trimmedString = [self.textInProgress stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [dictInProgress setObject:[trimmedString mutableCopy] forKey:kXMLReaderTextNodeKey]; // Reset the text self.textInProgress = [[NSMutableString alloc] init]; } // Pop the current dict [self.dictionaryStack removeLastObject]; } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { // Build the text value NSLog(@"string___%@",string); [self.textInProgress appendString:string]; } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { // Set the error pointer to the parser's error object self.errorPointer = parseError; } @end
相关推荐
使用NSXMLParser解析XML数据的一个Demo
xmlparsing-with-nsxmlparser-tutorial 你可以找到的NSXMLParser完整XMLParsing -教程这里 。 本教程由最好的The App Guruz提供。
ios xml解析 NSXMLParser。 NSXMLParser是基于SAX的解析方式。NSXMLParser采用了委托设计模式,因此他的实现类需要采用协议并支持委托。NSXMLParser解析XML需要委托NSXMLParserDelegate实现。
NULL 博文链接:https://eric-gao.iteye.com/blog/1590902
前言:本篇随笔介绍的是XML解析。 正文: 1、XML解析方式有2两种: DOM:一次性将整个XML数据加载进内存进行解析,比较... NSXMLParser:SAX方式解析,使用简单 2-3、本人基于苹果原生NSXMLParser封装好的XML解析
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if (...
代码例子(关于NSXMLParser 解析xml文件) xml 文件 通过NSXMLParser 解析成为数组 元素内容与属性可以获取到
Reachability 2.0版本,确认网络环境3G/WIFI 使用NSConnection下载数据 使用NSXMLParser解析xml文件
用于NSXMLParser的ReactiveCocoa扩展:一种简洁的,基于流的API,用于使用NSXMLParser解析XML。 围绕定义包装器,从而不再需要实现繁琐的委托方法。 应用所需的任何ReactiveCocoa魔术(请参阅 ): # import " ...
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if (...
通过SOAP 网络请求数据,并使用NSXMLParser解析Xml
XMLReader 该项目来自Troy Brant开发的组件,该...NSDictionary *dict = [XMLReader dictionaryForXMLData:data options:XMLReaderOptionsProcessNamespaces error:&error]; 要求 Xcode 4.4及更高版本,因为项目使
xml解析的两种常用方式, DOM解析:一次性将整个XML文档加载进内存,比较适合解析小文件,例如:GDataXml解析 ...SAX解析:从根元素开始,按顺序一个元素一个元素往下解析,比较适合解析大文件,例如:NSXMLParser解析
SHXMLParser 是一个基于 NSXMLParser 构建的易用的 XML 解析器,可转换 XML 数据到 Objective-C 对象。 标签:SHXMLParser
SwiftXMLParserExample如何使用Cocoa库中的NSXMLParser在Swift中解析XML的示例已针对Swift 2.0和Xcode7-Beta2更新这是用Swift编写的XML解析器的工作示例,但是使用Cocoa API来处理繁重的工作。 它部分基于Apple自己...
VMXMLParserSwift 2.0中的NSXMLParser包装器特征: 基于关闭响应作为字典数组Unicode支持截屏样例代码var url:String=...= nil){ println(error) }else{ println(tags!) } })样品回复({{description =“这个...”; id
一个使用ios自带的NSXMLParser的demo,课供新手参考学习
如果您熟悉NSXMLParser ,则此库是围绕它的简单包装。 从概念上讲,它提供了从XML到数组字典(又名哈希)的转换。 该API从中获得了很多启发。内容要求iOS 8.0 + / Mac OS X 10.9 + / tvOS 9.0 + / watchOS 2.0+ ...
在iPhone开发中,XML的解析有很多选择,iOS SDK提供了NSXMLParser和libxml2两个类库,另外还有很多第三方类库可选,例如TBXML、TouchXML、KissXML、TinyXML和GDataXML。问题是应该选择哪一个呢? 解析 XML 通常有两...
概述基于Swift的RSS阅读器,可将rss feed作为xml从远程服务器加载,并使用NSXMLParser对其进行解析。 解析完成后,它将数据加载到UITableView即显示标题和日期。 当单击标题时,它将转到详细信息页面,在该页面中,...