特定の xml 形式からデータを取得する必要があります。どうすればデータを取得できますか? XML へのリンクは次のとおりです。
1 に答える
1
まず、ヘッダー ファイルに URLConnection と passrsing のデリゲートを追加します。
追加するデリゲートは次のとおりです。
NSURLConnectionDelegate
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 データを扱うための優れたチュートリアルは次のとおりです:チュートリアル
于 2012-10-18T11:18:22.373 に答える