我从使用ASIHttpRequest连接到的网络服务器返回了以下非常简单的XML:
<element1>something</element1>
<element2>somethingelse</element2>
<element3>anotherthing</element3>
ASIHttpRequest可以将其作为NSData或NSString返回。我需要解析信息,最简单的方法是什么?
谢谢
最佳答案
有一些XML解析器可用于iOS NSXMLParser,libxml2(DOM和SAX),TBXML,KissXML。您可以参考http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project选择最佳的XML分析器(速度和内存占用)。最简单的是TBXML。 NSXMLParser也很容易。
NSXMLParser* xmlParser = [[NSXMLParser alloc] initWithData:receivedXMLData];//init NSXMLParser with receivedXMLData
[xmlParser setDelegate:self]; // Set delegate for NSXMLParser
[xmlParser parse]; //Start parsing
[xmlParser release];
//Delegate Methods
//Have a instance variable NSMutableString* currentString; to hold data between elements and NSMutableArray* elementsArray; to hold parsed data
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
elementsArray = [[NSMutableArray alloc] init];
}
//store all found characters between elements in currentString mutable string
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(!currentString)
{
currentString = [[NSMutableString alloc] init];
}
[currentString appendString:string];
}
//When end of XML tag is found this method gets notified
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"element1"])
{
[elementsArray addObject:currentString];
[currentString release],currentString=nil;
return;
}
if([elementName isEqualToString:@"element2"])
{
[elementsArray addObject:currentString];
[currentString release],currentString=nil;
return;
}
if([elementName isEqualToString:@"element3"])
{
[elementsArray addObject:currentString];
[currentString release],currentString=nil;
return;
}
[currentString release],currentString =nil;
}
//Parsing has ended
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"Content of Elements Array: %@",elementsArray);
[elementsArray release],elementsArray=nil;
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
UIAlertView* parseErrorAlert = [[UIAlertView alloc] initWithTitle:@"Parse Error" message:[NString stringWithFormat:"%@",[parseError localizedDescription]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[parseErrorAlert show];
[parseErrorAlert release];
}
您也有其他委托方法,例如parseErrorOccured。请参阅http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html
对于TBXML:http://tbxml.co.uk/TBXML/API.html
更新:实现parseError委托方法和有效的xml示例
您在代码中发布的XML是无效的XML(您可以在线检查XML验证:http://validator.w3.org/#validate_by_input),因此它将引发parseError。这是您发布有问题的XML的有效XML:
<?xml version="1.0"?>
<root>
<element1>something</element1>
<element2>somethingelse</element2>
<element3>anotherthing</element3>
</root>
关于objective-c - 在Objective-C中解析简单的XML,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7328070/