How do I detect a HTTP response, parse the xml and save to a NSString?

邮差的信 提交于 2019-12-23 02:56:08

问题


I've been trying to figure this out for weeks and i still get nothing. I am using the ASIHTTPRequest and ive successfully sent the data to a server and now I need to get the response XML,parse it and save the elements to each labeled NSString so I can post it to the server. Does anyone have an idea on how to do this?


回答1:


From looking at the How to Use page, I think what you want to do is implement methods that can be called when the request is complete. For example, say you have a method done: that you want to be called when your request completes. You can set that method as your "finished" selector on the request:

NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
[request setDelegate:self];
[request setDidFinishSelector:@selector(done:)];

Then later, you implement the done: method:

- (void)done:(ASIHTTPRequest *)request
{
   NSString *response = [request responseString];
}

This is all assuming you're sending the requests asynchronously; if you're using synchronous calls, you can just use the responseString property on the request.




回答2:


Get a copy of an XML library for the iPhone if you have other than trivial XML parsing needs.
I've used Google's GDataXMLNode for this before, but I would probably use KissXML for future work, because it's nearer NSXML (the Apple library which doesn't ship for the iphone unfortunately).

Here's a way to parse out the response, here I'm looking for errors you might typically see from a Rails server, along the lines of:

  <errors><error>Description of what went wrong</error></errors>

You can see that I get the 'request' object back from the library, and I feed the response string into a GDataXMLDocument.

   GDataXMLDocument* root = [[GDataXMLDocument alloc] initWithXMLString:[request responseString] options:0 error:nil];

   // Parse the error strings
   NSArray* errors = [root nodesForXPath:@"//errors/error" error:nil];

   // What is the first error string.... etc......
   NSString* firstError = [[errors objectAtIndex:0] stringValue];

The returned array here contains a list of nodes that match that path in the XML. If you're not familiar with XPath, it's not hard to learn, and useful for pulling data out of an XML response. Calling stringValue against the element returned in the array will return the text between the elements in the example above.

You can of course populate a dictionary, etc. with the returned XML data. Make sense?



来源:https://stackoverflow.com/questions/1456076/how-do-i-detect-a-http-response-parse-the-xml-and-save-to-a-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!