2012-01-12 61 views
1

我正在開發一個rss閱讀器,除了當我得到的元素的內容中有(')字符之類的字符時,一切正常。 我想我應該用某種形式的字符串函數替換或改變某種方式轉義字符的...解析XML,內容中的單引號字符ios5

例如,如果在XML我有:

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

我不明白「這是約翰的報紙」,但 「XX報」

這裏是我的代碼:

-(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提前。

回答

0

XML需要某些字符才能被轉義。例如,您不能在其中放入'>'字符,否則會混淆解析器。

你可以在HTML中看到這個例子。 你要找的轉義字符是:

&rsquo; 

您需要替換您的XML中的「字符。

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

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

我建議要通過名單,並確保沒有列出的字符出現在你的XML。

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

編輯:在這個問題上退房的答案How to parse strings containing ampersands with NSXMLParser?