可以使用NSXMLParser解析仅包含一个节点的xml文件

时间:2012-11-07 04:38:15

标签: iphone objective-c xml xml-parsing

作为初学者,我已经阅读了NSXMLParser并尝试实现解析器来解析xml

<?xml version="1.0" encoding="UTF-8"?>
<a>Some text here</a>

我的实施

-(OneNodeXMLParser*)initOneNodeXMLParser{

appDelegate = (OneNodeXMLParser*)[[UIApplication sharedApplication]delegate];
return self;
}

-(void)parser:(NSXMLParser*) parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
NSLog(@"%s",__PRETTY_FUNCTION__,nil);
if([elementName isEqualToString:@"a"]){
   // init some varibles
}
NSLog(@"Starting processing");
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"%s",__PRETTY_FUNCTION__,nil);
NSLog(@"%s",string);
}

   -(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
NSLog(@"%s",__PRETTY_FUNCTION__,nil);
NSLog(@"Finishing processing");
}

我应该修改什么才能成功解析文件?

1 个答案:

答案 0 :(得分:1)

.h文件中声明NSMutableString *store;

并更改以下方法:

-(void)parser:(NSXMLParser*) parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
  if([elementName isEqualToString:@"a"])
  {
     store = [[NSMutableString alloc] init];
  }
  NSLog(@"Starting processing");
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
  NSLog(@"%s",string);
   if (store != nil)
   {
     [store appendString:string];
   }
}

-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
 {
   NSLog(@"Finishing processing String : %@", store);
 }

您可以使用该字符串变量store以供将来使用。