0

这是我通过网络服务收到的 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>

我试图在我的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);
}

这有什么问题?,执行流程不在块内..

4

1 回答 1

2

更好的解决方案是使用 XML 解析器(例如NSXMLParser)而不是正则表达式。

</QuoteOfTheDay>但是要回答您的具体问题:您的正则表达式与 and 之间的空格(换行符和空格)不匹配<Author>。如果您将模式更改为

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

你会得到预期的输出。

于 2013-05-06T07:16:35.957 回答