如何从xml解析中获取数据

时间:2015-05-14 11:52:14

标签: ios xml-parsing

我正在尝试解析来自xml解析的数据,但它无法显示任何内容..

-(void)viewDidLoad {
    [super viewDidLoad];
    self.mdata=[[NSMutableData alloc]init];
    marr=[[NSMutableArray alloc]init];
    mwebcall =[[NSMutableArray alloc]init];
    NSString *urlstr=@"http://www.espncricinfo.com/rss/content/story/feeds/6.xml";

    NSURL *url1 = [NSURL URLWithString:urlstr];

    NSURLRequest *urlrequest=[[NSURLRequest alloc]initWithURL:url1 ];
    con = [[NSURLConnection alloc]initWithRequest:urlrequest delegate:self];

    [con start];
}
// Do any additional setup after loading the view, typically from a nib.



//#pragma mark-xmlmethods
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [mdata appendData:data];

}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.xmlparse=[[NSXMLParser alloc]initWithData:mdata];
    self.xmlparse .delegate=self ;
    [self.xmlparse parse];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
}
-(void)parserDidStartDocument:(NSXMLParser *)parser{

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

    if ([elementName isEqualToString:@"item"])
    {
        str=@"item";
    }
    else if ([elementName isEqualToString:@"title"])
    {   
        str=@"title";
    }   
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([str isEqualToString:@"item"])
    {
        str1=@"";
        str1=[str1 stringByAppendingString:string];`enter code here`
    }
    if ([str isEqualToString:@"title"])
    {
        str1=@"";
        str1=[str1 stringByAppendingString:string];
        NSLog(@"%@",str1);
    }`enter code here`

}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([str isEqualToString:@"item"])
    {
        [mwebcall addObject:str1];
        NSLog(@"%@",str1);
    }
    if ([str isEqualToString:@"title"])
    {
        [mwebcall addObject:str1];
        NSLog(@"%@",str1);
    }
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{

}

1 个答案:

答案 0 :(得分:1)

使用此GitHub library

NSString *url=@"http://www.lancers.jp/work";
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSDictionary *dict=[XMLParser dictionaryForXMLData:data error:nil];
NSLog(@"%@",[dict description]);

使用此代码并创建以下文件

<强> XMLParser.h

#import <Foundation/Foundation.h>

@interface XMLParser : NSObject<NSXMLParserDelegate>
{
    NSMutableArray *dictionaryStack;
    NSMutableString *textInProgress;
    NSError **errorPointer;
}

+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer;
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer;

@end

<强> XMLParser.m

#import "XMLParser.h"

NSString *const kXMLReaderTextNodeKey = @"text";

@interface XMLParser (Internal)

- (id)initWithError:(NSError **)error;
- (NSDictionary *)objectWithData:(NSData *)data;

@end

@implementation XMLParser

#pragma mark -
#pragma mark Public methods

+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)error
{
    XMLParser *reader = [[XMLParser alloc] initWithError:error];
    NSDictionary *rootDictionary = [reader objectWithData:data];
    [reader release];
    return rootDictionary;
}

+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error
{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    return [XMLParser dictionaryForXMLData:data error:error];
}

#pragma mark -
#pragma mark Parsing

- (id)initWithError:(NSError **)error
{
    if (self = [super init])
    {
        errorPointer = error;
    }
    return self;
}

- (void)dealloc
{
    [dictionaryStack release];
    [textInProgress release];
    [super dealloc];
}

- (NSDictionary *)objectWithData:(NSData *)data
{
    // Clear out any old data
    [dictionaryStack release];
    [textInProgress release];

    dictionaryStack = [[NSMutableArray alloc] init];
    textInProgress = [[NSMutableString alloc] init];

    // Initialize the stack with a fresh dictionary
    [dictionaryStack addObject:[NSMutableDictionary dictionary]];

    // Parse the XML
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    BOOL success = [parser parse];

    // Return the stack's root dictionary on success
    if (success)
    {
        NSDictionary *resultDict = [dictionaryStack objectAtIndex:0];
        return resultDict;
    }

    return nil;
}

#pragma mark -
#pragma mark NSXMLParserDelegate methods

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    // Get the dictionary for the current level in the stack
    NSMutableDictionary *parentDict = [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
    [dictionaryStack addObject:childDict];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    // Update the parent dict with text info
    NSMutableDictionary *dictInProgress = [dictionaryStack lastObject];

    // Set the text property
    if ([textInProgress length] > 0)
    {
        [dictInProgress setObject:textInProgress forKey:kXMLReaderTextNodeKey];

        // Reset the text
        [textInProgress release];
        textInProgress = [[NSMutableString alloc] init];
    }

    // Pop the current dict
    [dictionaryStack removeLastObject];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    // Build the text value
    [textInProgress appendString:string];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    // Set the error pointer to the parser's error object
    *errorPointer = parseError;
}

@end