解析XML,内容中的单引号字符,ios5



我正在开发一个rss阅读器,除了在我要获取的元素的内容中有一个类似(')的字符外,一切都很好。我想我应该使用某种字符串函数来替换或更改转义符。。。

例如,如果在xml中我有:

<desciption>this is John's newspaper</description>

我不知道"这是约翰的报纸",但知道""

这是我的代码:

-(id) loadXMLByURL:(NSString *)urlString
{
    rssFeeds            = [[NSMutableArray alloc] init];
    NSURL *url          = [NSURL URLWithString:urlString];
    NSData  *data       = [[NSData alloc] initWithContentsOfURL:url];
    xmlParser           = [[NSXMLParser alloc] initWithData:data];
    [xmlParser setDelegate:self];
    [xmlParser parse];
    return self;
}

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementname isEqualToString:@"item"])
    {
        currentFeed = [rssReader alloc];
    }
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementname isEqualToString:@"title"])
    {
        currentFeed.rssTitle = str1;
    }
    if ([elementname isEqualToString:@"description"])
    {
        currentFeed.rssDescription = currentNodeContent;
    }
    if ([elementname isEqualToString:@"pubDate"])
    {
        currentFeed.rsspubDate = currentNodeContent;
    }
    if ([elementname isEqualToString:@"item"])
    {
        [rssFeeds addObject:currentFeed];
        currentFeed = nil;
        currentNodeContent = nil;
    }
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[xmlParser rssFeeds] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    INrssCell *cell = (INrssCell *)[tableView dequeueReusableCellWithIdentifier:@"ingrCell"];
    rssReader *currectFeed = [xmlParser.rssFeeds objectAtIndex:indexPath.row];
    cell.titleLbl.text = currectFeed.rssTitle;
    cell.dateLbl.text = currectFeed.rsspubDate;
    cell.descLbl.text = currectFeed.rssDescription;
    return cell;
}

thanx。

XML要求转义某些字符。例如,您不能在中放入'>'字符,否则会混淆解析器。

您可以在HTML中看到这方面的示例。您要查找的转义字符是:

&rsquo;  

您需要替换XML中的"字符。

<description>this is John&rsquo;s newspaper</description>

来源:http://htmlhelp.com/reference/html40/entities/special.html

我建议浏览列表,并确保所列出的字符都不会出现在XML中。

NSString* contents = [NSString stringWithContentsOfURL:url 
                                              encoding:NSUTF8StringEncoding 
                                                 error:nil];
// You can pre-process(replace certain characters, ...) content of xml in here.
NSData* data = [contents dataUsingEncoding:NSUTF8StringEncoding];

编辑:看看这个问题的答案如何用NSXMLParser解析包含与号的字符串?

最新更新