0

作为初学者,我已经阅读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");
}

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

4

1 回答 1

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以供将来使用。

于 2012-11-07T04:54:25.113 回答