`
啸笑天
  • 浏览: 3469130 次
  • 性别: Icon_minigender_1
  • 来自: China
社区版块
存档分类
最新评论

NSXMLParser :xml to NSDictionary

 
阅读更多

 

#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

 

分享到:
评论
1 楼 ITabel 2016-11-05  
XML解析、XML直接转nsdictionary
还是用这个强大的库吧!!
http://www.cocoachina.com/bbs/read.php?tid-1706071.html
有多少层,转化多少层!!

不依赖于任何第三方库,小巧高效

相关推荐

    IOS XML类型转JSON类型

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*, NSString *&gt; *)...

    OC中JSON或XML解析

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData]; parser.delegate = self; [parser parse]; ``` 解析器的代理需要遵循NSXMLParserDelegate协议,实现相关方法来处理XML元素。 2. 实现代理...

    WFXMLParser:XML解析

    它不依赖于大型库如GDataXML或NSXMLParser,而是通过自定义的解析逻辑来处理XML,降低了内存占用和性能开销。 ### 3. 使用WFXMLParser 首先,你需要将WFXMLParser-master项目中的源代码添加到你的iOS项目中。接着...

    iOS xml解析和json解析demo

    总结一下,这个"iOS xml解析和json解析demo"将涵盖如何在iOS应用中解析XML数据,包括使用NSXMLParser和XMLParser,以及如何解析和序列化JSON数据,包括使用内置的JSONSerialization类和可能涉及的一些第三方库。...

    Objective-c对象组装XML

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if (...

    进入网络请求,对返回的XML数据进入处理

    3. 实现代理方法:`- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*, NSString...

    事件驱动的Xml解析

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*, NSString *&gt; *)...

    IOS应用源码——xmlparser.rar

    1. `- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*, NSString *&gt; *)...

    ios中xml解析demo

    例如,只需一行代码,XML内容就可以被解析成 NSDictionary 对象。 在iOS项目中集成XML解析库,通常通过CocoaPods或者Carthage进行管理。以CocoaPods为例,需要在Podfile中添加对应的库(如GDataXML),然后运行`pod...

    object c解析xml

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*, NSString *&gt; *)...

    iOS XMLReader

    NSString *xmlString = [NSString stringWithContentsOfFile:@"path_to_xml_file" encoding:NSUTF8StringEncoding error:nil]; NSDictionary *xmlDictionary = [XMLReader dictionaryWithXMLString:xmlString]; ``` ...

    iPhone编程解析xml

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*, NSString *&gt; *)...

    HJXMLPaeser.zip

    通过XMLReader这个类,开发者可以方便地将XML数据转化为易于处理的Objective-C对象,而无需直接与复杂的NSXMLParser API打交道。这对于处理XML格式的数据,尤其是在移动应用开发中,提供了极大的便利性。 总结起来...

    OC - XML数据解析转换成模型

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*, NSString *&gt; *)...

    xml解析demo

    3. **XMLDictionary**:这是一个第三方库,它将XML转换为易于操作的NSDictionary对象。通过这个库,XML数据可以快速转化为键值对,便于操作和理解。 4. **SWXMLHash**:另一个流行的第三方库,它提供了一种链式语法...

    iOSXML数据解析

    XMLReader是Objective-C中处理XML的一种高效方式,它是基于NSXMLParser的优化实现,提供了逐节点读取XML文档的功能,从而减少了内存消耗,尤其适合处理大型XML文件。在iOS中,XML解析通常有以下几种方式:...

    XML.zip_XML 解析_c xml_sbjson x_xml

    `NSXMLParser`是一个事件驱动的解析器,它会逐个处理XML文档的元素,触发相应的回调方法,例如`parser:didStartElement:`和`parser:foundCharacters:`等,开发者可以在这些回调中处理解析到的数据。 另一方面,JSON...

    IOS连接互联网JSON操作XML操作案例源码

    - `NSXMLParserDemo.zip`则直接指向了一个XML解析的示例,它演示了如何使用`NSXMLParser`进行XML数据解析。 学习这些知识点对于iOS开发者来说非常重要,因为它们涉及到应用程序如何与服务器进行数据交互,从而实现...

    XML文件转化成NSData对象的方法

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*, NSString *&gt; *)...

    GetProvinceCityAreaByXMLFile:一个简单的小例子,通过解析xml文件去实现选择省市区.其中还包括了一个用plist文件去实现省市区选择

    -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if (...

Global site tag (gtag.js) - Google Analytics