iphone - 无法使用 NSXML 解析器进行解析

标签 iphone objective-c ios xcode ipad

我有以下 XML 文件:

<?xml version="1.0"? encoding="UTF-8"?>
<api>
        <count count="55" />
        <spa>
            <opt>aa</opt>
            <opt>bb</opt>
            <opt>cc</opt>

        </spa>
</api>

M 使用以下代码行:

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"space.xml"];

NSData *data = [[NSData alloc] initWithContentsOfFile:path];

NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];

//Initialize the delegate.
XMLParser *theParser = [[XMLParser alloc] initXMLParser];

//Set delegate
[xmlParser setDelegate:theParser];

//Start parsing the XML file.
BOOL success = [xmlParser parse];

if(success)
    NSLog(@"No Errors");
else
    NSLog(@"Error Error Error!!!");

但是,m 在 gdb 中得到的输出为“error error error”。我是 Objective C 的新手,无法解决错误。有人可以帮忙吗??谢谢。

最佳答案

//尝试使用 NSXMLParser

NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:[NSURL URLWithString:@"YourURL"]];
[parser setDelegate:self];
[parser parse];

//以下是将为您获取数据的代表

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict

  {    
            if([elementName isEqualToString:@"spa"]){
           got = YES; //got is a BOOL and here we have encountere start tag i.e <spa>
     }
  }

    -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
     {
          if(got)
          {
                 NSLog(@"the Data is = %@",string);
          }
     }

    -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
     {
         if([elementName isEqualToString:@"spa"])
        {
           got = NO; //Here we have encountered the end tag </spa>
        }

     }

关于iphone - 无法使用 NSXML 解析器进行解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10882407/

相关文章:

iphone - 你能用 NSPredicate 指定 "select unique name from ..."吗?

ios - 如何让这个xib文件填满iPhone 6 plus的整个屏幕

iphone - 如何检查核心数据中的实体是否具有值 id?

iphone - iPhone SDK:使用coreAudio播放声音

iphone - 如何知道iPhone中的服务器回复?

ios - 如何在 iPad (UISplitViewController) ios xcode 中控制后退按钮导航

ios - 如何检测我的应用程序是否已在 didFinishLaunchingWithOptions 方法中启动以进行后台提取?

iOS 7.1 Sprite Kit AVAudioSession 进入后台时崩溃

ios - MPVolumeView 中的 showRouteButton 已弃用

ios - Restkit/Core Data 关系映射,实体到相同类型的实体(父/子)