-3

我需要从给定的 xml 格式中检索数据。如何检索数据?这是 XML 的链接

4

1 回答 1

1

首先,添加 URLConnection 的委托并在头文件中传递:

要添加的代表是:

  1. NSURLConnectionDelegate
  2. NSXMLParserDelegate

那么您必须调用 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

于 2012-10-18T11:18:22.373 回答