无法从xml格式检索数据

时间:2012-10-18 10:52:15

标签: objective-c ios xml xcode

我需要从给定的xml格式中检索数据。我该如何检索数据? Here is a link to the XML

1 个答案:

答案 0 :(得分:1)

首先,在头文件中添加URLConnection和pasrsing的委托:

代表添加是:

  1. NSURLConnectionDelegate
  2. NSXMLParserDelegate
  3. 然后你必须调用XML URL:

        NSURL *url = [NSURL URLWithString:URLString];
        NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
        NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
        [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setTimeoutInterval:10];
        NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        if( theConnection )
        {
            responseData = [[NSMutableData data] retain];
        }
    

    实现NSURLConnectionDelegate方法,如下所示:

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        NSLog(@"didReceiveResponse");
        [responseData setLength:0];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        NSLog(@"didReceiveData");
        [responseData appendData:data];
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        NSLog(@"didFailWithError = %@",[error description]);
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        NSLog(@"connectionDidFinishLoading");
    
        xmlParser= [[NSXMLParser alloc]initWithData:responseData];
        [xmlParser setDelegate:self];
        [xmlParser setShouldResolveExternalEntities: YES];
        [xmlParser parse];
    
        [responseData release];
        [connection release];
    }
    

    然后添加xmlParser委托方法:

    -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    //The tags in the xml data, the opening tags
    }
    
    -(void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string {
    //The data in tags
    }
    
    -(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qName {
    //The end of each tags
    }
    

    以下是处理XML数据的好教程:Tutorial