使用NSXMLParse解析Anchor标记和内容

时间:2014-04-14 11:13:09

标签: ios xml parsing nsxmlparser xmlnode

我想解析"比较中的html标签"节点

<comparison>
    <a href="/cgi-bin/amazon.cgi?B0050AMJYU">Amazon.com</a>
    ($34.36) |
    <a href="/cgi-bin/walmart.cgi?16904483">Walmart.com</a>
    ($34.36) |
    <a href="/cgi-bin/rakuten.cgi?219782579">Rakuten.com</a>
    ($34.36) |
    <a href="/cgi-bin/bestbuy1.cgi?mp1307815397">BestBuy.com</a>
    ($34.36)
</comparison>

我得到的输出是:

 BestBuy.com ($34.36)

预期产出:

Amazon.com ($34.36)  
Walmart.com ($34.36) 
Rakuten.com ($34.36)  
BestBuy.com ($34.36)

但我想显示所有这四个项目。

CODE

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    currentElementValue = [NSMutableString string];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    if ([elementName isEqualToString:@"item"]) {
        dealsListObj = [[DealsParsingObjects alloc] init];
    }

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    [currentElementValue appendString:string];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([elementName isEqualToString:@"short_title"]) {
        dealsListObj.itemTitle = currentElementValue;
        currentElementValue = nil;
    }
    else if ([elementName isEqualToString:@"final_price"]) {
        dealsListObj.price = currentElementValue;
        currentElementValue = nil;
    }
    //Detail view
    else if ([elementName isEqualToString:@"merchant"]) {
        dealsListObj.itemMerchant = currentElementValue;
        currentElementValue = nil;
    }
    else if ([elementName isEqualToString:@"getdeal"]) {
        dealsListObj.itemGetDeal = currentElementValue;
        currentElementValue = nil;
    }
    //comparison
    else if ([elementName isEqualToString:@"comparison"]) {
        dealsListObj.comparison = currentElementValue;
        currentElementValue = nil;

    }
    else if ([elementName isEqualToString:@"item"]) {
        [resultArray addObject:dealsListObj];
        [dealsListObj release];
        dealsListObj = nil;
        currentElementValue = nil;
    }
}

1 个答案:

答案 0 :(得分:0)

您的DealsParsingObjects课程似乎有一个名为NSMutableArray的{​​{1}}。当解析开始读取commentsArray元素时,您实例化该数组。

但是当解析器读取了<comparison>元素时,您将该值赋给名为<comparison>的属性;它没有被添加到数组中。作为一个默认的comparison属性(我的假设),每次解析器读完NSString元素时,它都会被重新分配。

修改:

每次读取新元素时都会调用

<comparison>。这也适用于parser:didStartElement:...标签。在该方法中,您重置<a>。因此,对于每个currentElementValue,该值基本上重置为空字符串。仅保留最后一个读取值,即最后一个<a>标记的值加上尾随文本。