iPhone中的XML解析

3

我刚开始接触XML解析。我完全不知道我们需要使用多少方法来进行XML解析,以及这些方法的作用是什么。我想要向Web服务发送输入,并通过使用XML解析将结果显示在我的文本字段中。


你可以很容易地找到如何开始的资源。我建议看一下NSXMLParser和它的代理方法。编码愉快。http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html - Jens Bergvall
这些方法都是委托,你不必处理它们所有。但是,您可能希望在范围内处理endelement和foundcharacters,以便您知道从xml中获取哪些项目。 - Praveen S
NSXMLParser是一个SAX解析器,相比许多DOM解析器,它更难使用。如果您只是从大型XML文档中提取少量数据,我建议使用TouchXML等解决方案而不是NSXMLParser。 - dtuckernet
这肯定会对你有所帮助 https://dev59.com/o0fRa4cB1Zd3GeqP70tX#12950155 请查看。 - Ravi_Parmar
7个回答

5

3
您应该使用以下方法:
- (void)parseXMLFileAtURL:(NSString *)URL { //own method from me, URL could be local file or internet website 
    itemsOfFeed = [[NSMutableArray alloc] init];
    NSURL *xmlURL = [NSURL URLWithString:URL];
    feedParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    [feedParser setDelegate:self];
    [feedParser setShouldProcessNamespaces:NO];
    [feedParser setShouldReportNamespacePrefixes:NO];
    [feedParser setShouldResolveExternalEntities:NO];
    [feedParser parse];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    //in case of an error
}

- (void)parserDidStartDocument:(NSXMLParser *)parser {
    // start to parse xml
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    feedElement = [elementName copy];
    if([elementName isEqualToString:@"item"]) { //main xml tag
        item = [[NSMutableDictionary alloc] init];
        feedTitle = [[NSMutableString alloc] init];
        feedDate = [[NSMutableString alloc] init];
        feedText = [[NSMutableString alloc] init];
        feedLink = [[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if([feedElement isEqualToString:@"title"]) {
        [feedTitle appendString:string];
    } else if([feedElement isEqualToString:@"link"]) { // some examples of tags
        [feedLink appendString:string];
    } else if([feedElement isEqualToString:@"content:encoded"]) {
        [feedText appendString:string];
    } else if([feedElement isEqualToString:@"pubDate"]) {
        [feedDate appendString:string];
    }
}

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if([elementName isEqualToString:@"item"]) {
        [item setObject:feedTitle forKey:@"title"];
        [item setObject:feedDate forKey:@"date"];
        [item setObject:feedText forKey:@"text"];       
        [item setObject:feedLink forKey:@"link"];
        [itemsOfFeed addObject:item];
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    [self.myTableView reloadData]; // for example reload table view
    [self writeArrayToFile]; //or write to a local property list
}

在您的头文件中:
NSMutableArray *itemsOfFeed;
NSXMLParser *feedParser;
NSMutableDictionary *item;
NSMutableString *feedElement;
NSMutableString *feedTitle, feedDate, feedText, feedLink; //strings of your tags

接下来你会看到:

  • NSArray
    • NSDictionary
      • 对象a
      • 对象b
      • 对象c

只需访问 '对象a' 并将其放入您的文本字段中即可。

希望这个代码示例能够帮助您。


代码示例很棒!但是使用DOM解析器会更容易。如果用户只需要一个值,那么使用类似Touch XML的解决方案可以用4行代码替代所有这些代码。 - dtuckernet
当然,使用Touch XML可能更容易 :) 但是我在Touch XML不那么易于使用的时候创建了这段代码。 - tharkay
这个方法"[self.mWNetowrk makeRequsetWithURL:URL_SERVICES type:ReqLogin paramDictionary:paramDic delegate:self];"的意思是什么?它有什么用处? - PradeepG
什么是ivar mWNetwork?我认为它将向“URL_SERVICES”服务器发送请求。其余部分应该是不言自明的:它需要登录,请求需要参数字典,委托是您的实现类。 - tharkay

2

我有一个演示应用程序,可以将静态XML解析为UITableView,我认为这篇文章肯定会对你有所帮助。


2

2

你好,我个人更喜欢使用NSXMLParser。

编写自己的代码,使用NSXMLParserDelegate方法实现。

但仍然有一些第三方库可用。这里有一个很好的示例,可以比较所有这些解析器之间的区别,并且还有很好的解释。代码也在那里提供。

希望这对你有所帮助。

-Mrunal


0

试试这个:

XMLReader.h

//
//  XMLReader.h
//
//

#import <Foundation/Foundation.h>

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

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

@end

XMLReader.m

//
//  XMLReader.m
//

#import "XMLReader.h"

//NSString *const kXMLReaderTextNodeKey = @"text";

@interface XMLReader (Internal)

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

@end

@implementation XMLReader

#pragma mark -
#pragma mark Public methods

+ (NSDictionary *)dictionaryForPath:(NSString *)path error:(NSError **)errorPointer
{
    NSString *fullpath = [[NSBundle bundleForClass:self] pathForResource:path ofType:@"xml"];
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:fullpath];
    NSDictionary *rootDictionary = [XMLReader dictionaryForXMLData:data error:errorPointer];

    return rootDictionary;
}

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

    return rootDictionary;
}

+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error
{
    NSArray* lines = [string componentsSeparatedByString:@"\n"];
    NSMutableString* strData = [NSMutableString stringWithString:@""];

    for (int i = 0; i < [lines count]; i++)
    {
        [strData appendString:[[lines objectAtIndex:i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    }

    NSData *data = [strData dataUsingEncoding:NSUTF8StringEncoding];
    return [XMLReader 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];
    [parser release];

    // 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
    NSMutableDictionary *childDict = [NSMutableDictionary dictionary];

    // Initialize child dictionary with the attributes, prefixed with '@'
    for (NSString *key in attributeDict) {
        [childDict setValue:[attributeDict objectForKey:key]
                     forKey:key];
    }

    // 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];

    // Pop the current dict
    [dictionaryStack removeLastObject];

    // Set the text property
    if ([textInProgress length] > 0){
        if ([dictInProgress count] > 0){
            [dictInProgress setObject:textInProgress forKey:kXMLReaderTextNodeKey];
        }
        else{
            // Given that there will only ever be a single value in this dictionary, let's replace the dictionary with a simple string.
            NSMutableDictionary *parentDict = [dictionaryStack lastObject];
            id parentObject = [parentDict objectForKey:elementName];

            // Parent is an Array
            if ([parentObject isKindOfClass:[NSArray class]]){
                [parentObject removeLastObject];
                [parentObject addObject:textInProgress];
            }

            // Parent is a Dictionary
            else{
                [parentDict removeObjectForKey:elementName];
                [parentDict setObject:textInProgress forKey:elementName];
            }
        }

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

    // If there was no value for the tag, and no attribute, then remove it from the dictionary.
    else if ([dictInProgress count] == 0){
        NSMutableDictionary *parentDict = [dictionaryStack lastObject];
        [parentDict removeObjectForKey:elementName];
    }
}

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

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

@end

使用方法:

NSMutableDictionary *yourDic= (NSMutableDictionary *)[XMLReader dictionaryForXMLData:yourData error:&error];

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接