所以我有一个XML文件,其中包含来自对象的许多实例的数据。我正在解析这个文件,但只想要带有元素标签“Content”的数据
我正在使用NSXMLParser
,因此我有方法parserDidStartDocument
,didStartElement
,foundCharacters
和didEndElement
所以这是我当前的实现
在标题中:
@property (strong) NSMutableArray* AssetJSONObjects;
实施中:
BOO
l grabContent = NO;
- (void) parserDidStartDocument:(NSXMLParser *)parser {
NSLog(@"parserDidStartDocument");
self.AssetJSONObjects = [NSMutableArray new];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
NSLog(@"didStartElement --> %@", elementName);
if([elementName isEqual:@"Content"])
{
grabContent = YES;
}
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSLog(@"foundCharacters --> %@", string);
if(grabContent)
{
[self.AssetJSONObjects addObject:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSLog(@"didEndElement --> %@", elementName);
if(grabContent)
{
grabContent = NO;
}
}
- (void) parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"parserDidEndDocument");
}
所以这是我的问题:我正在声明/初始化我的数组,AssetJSONObjects
是合法的吗?我正在初始化我的bool grabContent
是合法的吗?有没有更好的方法从特定标签中获取数据?
答案 0 :(得分:0)
找到便宜的路线,只需跟踪一个全局布尔值并在找到标签时设置它
相关代码:
BOOL grabContent = NO;
- (void) parserDidStartDocument:(NSXMLParser *)parser {
self.AssetJSONObjects = [NSMutableArray new];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if([elementName isEqual:@"Content"])
{
grabContent = YES;
}
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(grabContent)
{
NSDictionary *JSONObject =
[NSJSONSerialization JSONObjectWithData: [string dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: nil];
if (JSONObject)
{
[self.AssetJSONObjects addObject:JSONObject];
}
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if(grabContent)
{
grabContent = NO;
}
}
- (void) parserDidEndDocument:(NSXMLParser *)parser {
self.notifications = [self convertRawJSONToNotifications:self.AssetJSONObjects];
if(self.notifications != nil)
{
self.notificationCompletionHandler(self.notifications, self.numNewNotifications);
}
}