objective-c - iOS:使用 NSXMLParser 从 HTTP 解析 xml

标签 objective-c ios nsxmlparser

这是第一次使用 NSXMLParser,想知道您是否给我一些从 http 请求中解析返回的 xml 的指导,如下所示:

<?xml version="1.0" ?>
<theresponse>
 <status>OK</status>
 <pricing currency="USD" symbol="$">
   <price class="items">24.00</price>
   <price class="shipping">6.00</price>
   <price class="tax">1.57</price>
 </pricing>
</theresponse>

我知道解析委托(delegate)方法的基础知识,我只是想知道 didEndElement/foundCharacters/didStartElement 中用于检索上述项目(货币/项目/运输/税)的代码是什么样的?非常感谢任何帮助。

最佳答案

这比一些标准的 NSXMLParser 代码要复杂一些;因为本质上,当您查找“shipping”时,您需要“6.00”,但这两条数据会在不同的委托(delegate)方法中返回给您,这是正常的。但通常该元素会被命名为“shipping”,因此在 parser:didEndElement:namespaceURI:qualifiedName: 中,您将自动获得传递到方法中的元素名称。

解决方案看起来很简单,有一个 _currentAttributes ivar 并在 parser:didStartElement:namespaceURI:qualifiedName:attributes: 中执行类似 _currentAttributes = attributeDict; 然后在 didEndElement: 方法中处理它。然而,即使在这种相当简单的 XML 上,这种样式也很容易被破坏。

我的处理方法是存储传递到 didStartElement: 的属性字典,并将其设置在字典中作为元素名称键的对象。将此样式与 NSMutableString 作为某种字符缓冲区的标准使用相结合,允许您将所有逻辑放入 didEndElement: 方法中。

旁注:我也很喜欢让我的 NSXMLParserDelegate 类成为 NSXMLParser 子类,就像这个一样。然而,如果不是的话,委托(delegate)方法将是相同的。

ItemParser.h

#import <Foundation/Foundation.h>
@interface ItemParser : NSXMLParser <NSXMLParserDelegate>
@property (readonly) NSDictionary *itemData;
@end

ItemParser.m

#import "ItemParser.h"
@implementation ItemParser {
    NSMutableDictionary *_itemData;
    NSMutableDictionary *_attributesByElement;
    NSMutableString *_elementString;
}
-(NSDictionary *)itemData{
    return [_itemData copy];
}
-(void)parserDidStartDocument:(NSXMLParser *)parser{
    _itemData = [[NSMutableDictionary alloc] init];
    _attributesByElement = [[NSMutableDictionary alloc] init];
    _elementString = [[NSMutableString alloc] init];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    // Save the attributes for later.
    if (attributeDict) [_attributesByElement setObject:attributeDict forKey:elementName];
    // Make sure the elementString is blank and ready to find characters
    [_elementString setString:@""];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    // Save foundCharacters for later
    [_elementString appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    if ([elementName isEqualToString:@"status"]){
        // Element status only contains a string i.e. "OK"
        // Simply set a copy of the element value string in the itemData dictionary
        [_itemData setObject:[_elementString copy] forKey:elementName];
    } else if ([elementName isEqualToString:@"pricing"]) {
        // Pricing has an interesting attributes dictionary 
        // So copy the entries to the item data
        NSDictionary *attributes = [_attributesByElement objectForKey:@"pricing"];
        [_itemData addEntriesFromDictionary:attributes];
    } else if ([elementName isEqualToString:@"price"]) {
        // The element price occurs multiple times.
        // The meaningful designation occurs in the "class" attribute.
        NSString *class = [[_attributesByElement objectForKey:elementName] objectForKey:@"class"];
        if (class) [_itemData setObject:[_elementString copy] forKey:class];
    }
    [_attributesByElement removeObjectForKey:elementName];
    [_elementString setString:@""];
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
    _attributesByElement = nil;
    _elementString = nil;
}
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
    NSLog(@"%@ with error %@",NSStringFromSelector(_cmd),parseError.localizedDescription);
}
-(BOOL)parse{
    self.delegate = self;
    return [super parse];
}
@end

为了测试,我将您上面发布的 XML 存储到名为“ItemXML.xml”的文件中。并使用以下代码对其进行了测试:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"ItemXML" withExtension:@"xml"];
ItemParser *parser = [[ItemParser alloc] initWithContentsOfURL:url];
[parser parse];
NSLog(@"%@",parser.itemData);

我得到的结果是:

{
    currency = USD;
    items = "24.00";
    shipping = "6.00";
    status = OK;
    symbol = "$";
    tax = "1.57";
}

关于objective-c - iOS:使用 NSXMLParser 从 HTTP 解析 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036496/

相关文章:

ios - InApp Purchase 产品列表不会在 iPhone 应用程序中加载

iOS 8 如何防止 Spritekit 帧率下降

iphone - Objective-C iPhone 应用程序 EXC_BREAKPOINT (SIGTRAP)

ios - 使用 NSXMLParser 解析复杂的 XML 结构

iphone - 我正在解析 XML 并收到警告

c - 将指向数组的指针传递给 glGenBuffers

ios - 添加 View Controller

iphone - 不应出现注册屏幕

objective-c - 如何通过 CGRect 过滤 NSArray 中的 CGPoints

iphone - iOS - 为每个 tableView 行解析多个 XML 文件