2013-05-06 69 views
0

這裏通過Web服務收到了我的XML ..問題與XML解析使用正則表達式

<?xml version="1.0" encoding="utf-8"?> 
<Quotes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://swanandmokashi.com"> 
    <QuoteOfTheDay>Hit any user to continue.</QuoteOfTheDay> 
    <Author>Fuzzel Fish Administration Page</Author> 
</Quotes> 

和IM試圖通過這在我的connectionDidFinishLoading解析它:...

{    
webData_str=[[NSString alloc]initWithData:webData encoding:NSUTF8StringEncoding]; 
NSString *pattern = @"<QuoteOfTheDay>(.*)</QuoteOfTheDay><Author>(.*)</Author>"; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern 
         options:NSRegularExpressionCaseInsensitive                   error:nil]; 

__block NSString *QuoteString,*author= nil; 

[regex enumerateMatchesInString:webData_str options:0 range:NSMakeRange(0, [webData_str length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) { 

    // not executing... 

    if (0 < [match numberOfRanges]) { 
     NSRange range = [match rangeAtIndex:1]; 
     QuoteString = [webData_str substringWithRange:range]; 


     NSRange range1 = [match rangeAtIndex:2]; 
     author = [webData_str substringWithRange:range1];   

    } 
}];   

final=[NSString stringWithFormat:@"\n%@\n%@",QuoteString,author]; 
NSLog(@"Final--- %@",final); 
} 

什麼是錯的這個? ,執行流程不會在塊內。

回答

2

更好的解決方案是使用XML解析器(例如NSXMLParser)而不是常規的 表達式。

但要回答您的具體問題:您的正則表達式與</QuoteOfTheDay><Author>之間的空白(換行符和空格)不匹配。如果將圖案更改爲

NSString *pattern = @"<QuoteOfTheDay>(.*)</QuoteOfTheDay>\\s*<Author>(.*)</Author>"; 

您將獲得預期的輸出。

+0

完美..感謝..是NSXMlParser會更好的選擇,但作爲標籤數只有兩個我會選擇正則表達式.. – BaSha 2013-05-06 08:19:11