开发者

How to parse a locally stored XML file in iPhone?

How to parse a locally stored XM开发者_运维百科L file in iPhone?

please help me with this using code snippets


I have used NSXMLParser and i achieved it. I have r.xml file in my resource. I have just parsing the title and displayed using NSXMLParser.

      r.xml:

      <rss>
      <eletitle > My Xml Program  </eletitle>
      </rss>

Here my sample code is,

@interface:

  NSXMLParser *rssparser;

  NSMutableArray *stories;
  NSMutableDictionary *item;
  NSMutableString *currrentTitle;
  NSString *currentElement;

@implementation:

    -(void) viewDidAppear:(BOOL) animated
     {
           [self parseXMLFileAtURL];
     }

     -(void) parseXMLFileAtURL 
     {
         stories = [[NSMutableArray alloc] init];

         NSURL *xmlURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"r" ofType:@"xml"]];
         rssparser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
        [rssparser setDelegate:self];
        [rssparser setShouldProcessNamespaces:NO];
        [rssparser setShouldReportNamespacePrefixes:NO];
        [rssparser setShouldResolveExternalEntities:NO];
        [rssparser parse];

    }

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

     currentElement = [elementName copy];
     if([elementName isEqualToString:@"rss"]);
     {
         item = [[NSMutableDictionary alloc] init];
         currrentTitle = [[NSMutableString alloc] init];
     }
 }


    -(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *) string
     {
            if([currentElement isEqualToString:@"eletitle"])
            {
                 [currrentTitle appendString:string];
            }
      }

      - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ 

      if([elementName isEqualToString:@"rss"])
      {
             [item setObject:currrentTitle forKey:@"eletitle"];
             [stories addObject:[item copy]];
      }
   }

     - (void)parserDidEndDocument:(NSXMLParser *)parser
     {
              NSLog(@"The currrentTitle is %@",currrentTitle);

     }

Best of Luck.


I'm sorry I cannot give you any snippet now, but in one project I did some time ago, we used the touchXML library.

http://code.google.com/p/touchcode/wiki/TouchXML

With this, parsing XML was pretty easy.

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜