解析时没有找到元素?

时间:2011-04-12 15:11:35

标签: xml ios ios4 nsxmlparser

我是iPhone编程的新手,但是,我一直在研究我的问题并且找不到解决方案......

基本上,我正在尝试解析一个我无法控制的URL,该URL在其页面源中具有以下所需信息:

<tr style=" ">

<td valign="top" style="  ">            
<p style="  ">
4/10/2011
</p>
</td>           
<td valign="top" style="  ">            
<p style="  ">
-18
</p>
</td>           
<td valign="top" style="  ">            
<p style="  ">
21%
</p>
</td>           
<td valign="top" style="  ">            
<p style="  ">
39%
</p>
</td>           
<td valign="top" style="  ">            
<p style="  ">
45%
</p>
</td>           
<td valign="top" style="  ">            
<p style="  ">
54%
</p>
</td>
</tr>`      

在正确创建与网站的连接后,我将数据放在一起并尝试解析:

//This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[xmlData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
/*
//We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[[NSString alloc] initWithData:xmlDat encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"xmlCheck = %@", xmlCheck);
//Check was Successful!
*/

//Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
[parser setDelegate:self];
//Tell it to start parsing - the document will be parsed and the delegate of NSXMLParser will get all of
//its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
//The parser is done (it blocks until done), you can release it immediately
[parser release];
}

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *) qName
attributes:(NSDictionary *) attributeDict 
{
NSLog(@"StartedParsing");

//if ([elementName isEqualToString:@"tr"]) {
if (elementName) {
NSLog(@"found element!");
titleString = [[NSMutableString alloc] init];
}
}

您会注意到,我首先尝试搜索元素'tr',但后来切换到查找URL中的任何元素。没有任何内容打印到我的控制台窗口,这使我认为我的解析器没有找到任何元素 现在,如果我在以下网站上尝试相同的代码:http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml,则会找到许多不同的元素。这让我相信URL可能需要采用某种格式。有人能帮助我吗?

提前致谢!

P.S。 - 我还实现了'foundCharacters'和'didEndElement'解析器函数,但由于我的解析器似乎没有找到任何元素,因此无法使用它们。

1 个答案:

答案 0 :(得分:0)

html是无效的XML,但我认为这是一个简单的修复,添加xml开始标记,如:

<?xml version="1.0" encoding="utf-8"?> 
<tr style=" ">
snipped for space...
</tr>`