0

我有一个 iPhone 应用程序,这就是我使用 NSXMLParser 解析 RSS 提要中的标题的方式:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
        currentString = [[NSMutableString alloc] init];
        [self setTitle:currentString];
}

这工作得很好。现在我正在处理另一个包含带有
标签的标题的提要,我想删除它们。我在 StackOverflow 上看到了不同的问题,例如THIS
,它提供了用空字符串替换标签的代码。这就是我修改代码的方式:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    currentString = [[NSMutableString alloc] init];
    currentString = [[currentString stringByReplacingOccurrencesOfString:@"<br>" withString:@""] mutableCopy];
    [self setTitle:currentString];
}

但这不起作用,并且在不删除
标签的情况下在输出中显示相同的文本。谁能指出我做错了什么,我该如何纠正?

4

1 回答 1

0

我认为您应该尝试这些功能之一,这可能对您有帮助

#pragma mark -
#pragma mark - Remove HTML Tags
- (NSString *)stringByStrippingHTML:(NSString *)inputString
{
    NSMutableString *outString = [[[NSMutableString alloc] initWithString:inputString] autorelease];

    if ([inputString length] > 0)
    {
        NSRange r;

        while ((r = [outString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
        {
            [outString deleteCharactersInRange:r];
        }
    }

    return outString;
}

- (NSString *)stripTags:(NSString *)str
{
    NSMutableString *html = [NSMutableString stringWithCapacity:[str length]];

    NSScanner *scanner = [NSScanner scannerWithString:str];
    scanner.charactersToBeSkipped = NULL;
    NSString *tempText = nil;

    while (![scanner isAtEnd])
    {
        [scanner scanUpToString:@"<" intoString:&tempText];

        if (tempText != nil)
            [html appendString:tempText];

        [scanner scanUpToString:@">" intoString:NULL];

        if (![scanner isAtEnd])
            [scanner setScanLocation:[scanner scanLocation] + 1];

        tempText = nil;
    }

    return html;
}
于 2013-11-01T06:51:59.397 回答