Desperate for NSXMLParser Guidance - iphone

I previously asked this question XMLParser Advice.
However I am still unable to get it to function properly....
So I guess I will start from scratch:
Located at a certain URL is an XML Tree that looks like this
<result>
//stuff that I dont need
<title>
//thing that I do need
</title>
//stuff that I dont need
<body>
//thing that I do need
</body>
<result>
How the heck do I go about parsing that?
The (useless) code I have so far can be found in the link at the top of this question.
Thank you for your time.

Write a simple class, which will be the parser's delegate.
#interface YourObject : NSObject <NSXMLParserDelegate> {
NSString *title, *body; // object attributes
NSXMLParser *parser; // will parse XML
NSMutableString *strData; // will contains string data being parsed
}
#property(readwrite, copy) NSString *title, body;
// will be used to set your object attributes
-(void)fetchValuesAtURL:(NSString *)url;
#end
The fetchValuesAtURL: method will initiate the parse operation.
#implementation YourObject
#synthesize title, body;
-(id)init {
self = [super init];
if(self) {
title = #"";
body = #"";
parser = nil;
strData = [[NSMutableString alloc] initWithCapacity:10];
}
return self;
}
-(void)fetchValuesAtURL:(NSString *)url {
if(parser) {
[parser release];
}
NSURL *xmlURL = [NSURL URLWithString:url];
parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[parser setDelegate:self];
[parser parse];
}
-(void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict {
// element is about to be parsed, clean the mutable string
[strData setString:#""];
}
// the probably missing method
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
// content (or part of) has been found, append that to the current string
[strData appendString:string];
}
-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
// element has been parsed, test the element name
// and store strData accordingly
if([elementName isEqualToString:#"title"]) {
self.title = strData;
}
else { // or else if, here you got two elements to parse
self.body = strData;
}
}
-(void)dealloc {
[title release];
[body release];
[strData release];
if(parser) {
[parser release];
}
[super dealloc];
}
#end
Then :
YourObject *obj = [[YourObject alloc] init];
[obj fetchValuesAtURL:#"http://www.site.com/xml/url"];
NSXMLParser's delegate is able to do many more things, as described in Event-Driven XML Programming Guide from Apple.
For complete reference on delegate methods, see NSXMLParserDelegate Protocol Reference.

Related

Saving XML Parsed data to NSMutableDictionary Best Practice

This question might have been asked frequently but I have read almost all of them and yet couldn't figure out a solution for my case.
I plan to save the parsed data to a NSMutableDictionary. Parser works ok and If I get a log it shows all data parsed. the problem is the last Item only saves in the NSDictionary. I can guess that I placed the dictionary in a wrong method but I can't figure out a better solution for saving. I use dictionary in order to hold the name and the text of element. here is my code :
#implementation Parser
#synthesize currentElementPointer, rootElement;
#synthesize dictionary;
-(id)initParser
{
if(self = [super init]) {
tvc = (TimeTableViewController*)[[UIApplication sharedApplication]delegate];
APUAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
context = [appDelegate managedObjectContext];
[self deleteAllObjects:#"TimeTable"];
}
return self;
}
#pragma mark -
#pragma mark PARSER
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
self.parsing = YES;
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"intake"])
{
NSString *name = attributeDict[#"name"];
self.parsing = [name isEqualToString:[self sendIntakeToParser]];
}
if(![self isParsing]) return;
if(self.rootElement == nil) {
self.rootElement = [[List alloc]init];
self.currentElementPointer = self.rootElement;
} else {
List *newList = [[List alloc]init];
newList.parent = self.currentElementPointer;
[self.currentElementPointer.subElements addObject:newList];
self.currentElementPointer = newList;
}
self.currentElementPointer.name = elementName;
self.currentElementPointer.attributes = attributeDict;
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(![self isParsing]) return;
if([self.currentElementPointer.text length] > 0) {
self.currentElementPointer.text = [self.currentElementPointer.text stringByAppendingString:string];
} else {
self.currentElementPointer.text = string;
}
dictionary = [[NSMutableDictionary alloc]init];
[dictionary setObject:[self.currentElementPointer text] forKey:[self.currentElementPointer name]];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([self isParsing])
{
self.currentElementPointer = self.currentElementPointer.parent;
} else if ([elementName isEqualToString:#"intake"])
{
self.parsing = YES;
}
}
This is my xml structure:
The source of your problem is that you re-instantiate your dictionary with each call to parser:foundCharacters: which will be called at least once per element that has text. One thing you could do is move the dictionary instantiation to parser:didStartElement:... whenever elementName is equal to #"timetable", instantiate a mutable array in parser:didStartDocument: and then, in parser:didEndElement:..., if the elementName is `#"timetable", add it to your array.
An example of this is shown below:
Parser.h:
#import <Foundation/Foundation.h>
#interface Parser : NSObject <NSXMLParserDelegate>
- (void)parseData:(NSData *)data;
#end
Parser.m:
#import "Parser.h"
#interface Parser ()
#property (nonatomic,strong) NSMutableArray *timetableDictionaries;
#property (nonatomic,strong) NSMutableDictionary *currentTimetableDictionary;
#property (nonatomic,copy) NSString *currentElementName;
#end
#implementation Parser
- (void)parseData:(NSData *)data
{
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
self.timetableDictionaries = [NSMutableArray array];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
self.currentElementName = elementName;
if ([elementName isEqualToString:#"timetable"]) {
self.currentTimetableDictionary = [NSMutableDictionary dictionary];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (self.currentElementName) {
NSString *existingCharacters = self.currentTimetableDictionary[self.currentElementName] ? : #"";
NSString *nextCharacters = [existingCharacters stringByAppendingString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
if ([nextCharacters length] > 0) {
self.currentTimetableDictionary[self.currentElementName] = nextCharacters;
}
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"timetable"]) {
[self.timetableDictionaries addObject:self.currentTimetableDictionary];
self.currentTimetableDictionary = nil;
}
self.currentElementName = nil;
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"timetable dictionaries = %#",self.timetableDictionaries);
}
#end
I tested the above class with the following file:
<weekof week="2013-07-29">
<intake name="APCF1304">
<timetable>
<date>SOME DATE</date>
<time>SOME TIME</time>
<lecturer>SOME LECTURER</lecturer>
</timetable>
<timetable>
<date>ANOTHER DATE</date>
<time>ANOTHER TIME</time>
<lecturer>ANOTHER LECTURER</lecturer>
</timetable>
</intake>
</weekof>
And it gave the following output:
2013-08-11 11:50:03.205 MyParser[25368:c07] timetable dictionaries = (
{
date = "SOME DATE";
lecturer = "SOME LECTURER";
time = "SOME TIME";
},
{
date = "ANOTHER DATE";
lecturer = "ANOTHER LECTURER";
time = "ANOTHER TIME";
}
)
However, you've built a tree of the document already, presumably for another purpose, so you could just re-use that at the end of your parsing to build your dictionaries. For example, if you just wanted dictionaries for each timetable, you could do something that looked like this, in pseudocode:
dictionaries = [new mutable array]
element = self.root
[extract dictionaries from: element to:dictionaries]
implementation of extractDictionariesFrom:element to:dictionaries:
if any subelement has non-nil text:
item = [new mutable dictionary]
for each sub element:
item[element name] = element text
[add item to dictionaries]
else
for each subelement:
[extract dictionaries from: subelement to: dictionaries]
Then you could discard the use of the mutable dictionary in your parser callback.

How to display the xml parsing data in the UItextfield in iphone

I am able to parse the xml data and able to display it in the console, but not able to display that data in the UITextField or in UILabel.
I tried to assign to textfield in the viewDidLoad method also.
The following is my code,
NSMutableString *currentNodeContent;
NSXMLParser *parser;
ViewController *currentProfile;
bool isStatus;
ViewController *xmlParser;
-(id)loadXMLByURL:(NSString *)urlString
{
_profile = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"profileinfo"])
{
currentProfile = [ViewController alloc];
isStatus = YES;
}
if([elementName isEqualToString:#"first_name"])
{
currentProfile = [ViewController alloc];
isStatus = YES;
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"first_name"])
{
currentProfile.firstName = currentNodeContent;
NSLog(#"%#",currentProfile.firstName);
first_Name.text = currentNodeContent;//UITextField
first_name.text = currentNodeContent;//Label
}
if([elementName isEqualToString:#"last_name"])
{
currentProfile.lastName = currentNodeContent;
NSLog(#"%#",currentProfile.lastName);
last_Name.text = currentProfile.lastName;
}
if([elementName isEqualToString:#"profileinfo"])
{
[self.profile addObject:currentProfile];
currentProfile = nil;
currentNodeContent = nil;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
xmlParser = [[ViewController alloc] loadXMLByURL:#"http://www.mxxxxx.net/xxx/xxxxx.aspx?type=proifileinfo&loginid=xxx#gmail.com"];
}
Instead of assigning the values directly to the 'UITextField' or 'UILabel', have the values stored in a string. And when the parsing action completed, assign the string value to the 'UITextField' or 'UILabel'; Probably you should do that in '-viewWillAppear' method :-)
Create a IBOutlet UILabel *label; in the interface, connect it in Interface Builder, and then you can set the text of it by label.text = #"Anything";
I have also the same problem while parsing XML parser.
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
You are using the above line to trim spaces and tabs. But sometimes It does not work.
So, I implement the following code. The code may be useful to you.
NSString *sname = [currentNodeContent stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSString *actualString = [sname stringByReplacingOccurrencesOfString:#"\t" withString:#""];
Then pass the actualString to whatever you required.

NSXMLParser divides strings containing foreign(unicode) characters

I have ran into a peculiar problem with NSXMLParser.
For some reason it cuts out all the characters in front of all the norwegian characters æ, ø and å.
However, the problem seems to be the same with all non a-z characters.(All foreign characters)
Examples:
Reality: Mål
Output: ål
Reality: Le chant des sirènes
Output: ènes
Heres an example from the log where I have printed out the string from:
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
Log:
2012-02-22 14:00:01.647 VotePlayClient[2776:207] found characters: Le chant des sir
2012-02-22 14:00:01.647 VotePlayClient[2776:207] found characters: ènes
You can clearly see that it jumps to a new line whenever it encounters a foreign letter.
I believe that I have to figure out how to append the string or something to that effect.
Here are the NSXMLParser files:
SearchXMLParser.h
#import <Foundation/Foundation.h>
#import "Search.h"
#interface SearchXMLParser : NSObject <NSXMLParserDelegate>
{
NSMutableString *currentNodeContent;
NSMutableArray *searchhits;
NSMutableArray *trackhits;
NSXMLParser *parser;
Search *currentSearch;
}
#property (readonly, retain) NSMutableArray *searchhits;
#property (readonly, retain) NSMutableArray *trackhits;
-(id) loadXMLByURL:(NSString *)urlString;
#end
SearchXMLParser.m
#import "SearchXMLParser.h"
#import "Search.h"
#implementation SearchXMLParser
#synthesize searchhits, trackhits;
-(id) loadXMLByURL:(NSString *)urlString
{
searchhits = [[NSMutableArray alloc] init];
trackhits = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementname isEqualToString:#"track"])
{
currentSearch = [Search alloc];
}
if ([elementname isEqualToString:#"track"])
{
currentSearch.trackurl = [attributeDict objectForKey:#"href"];
}
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementname isEqualToString:#"name"])
{
[trackhits addObject:currentNodeContent];
}
if ([elementname isEqualToString:#"track"])
{
currentSearch.track = [trackhits objectAtIndex:0];
currentSearch.artist = [trackhits objectAtIndex:1];
currentSearch.album = [trackhits objectAtIndex:2];
[trackhits removeAllObjects];
[searchhits addObject:currentSearch];
[currentSearch release];
currentSearch = nil;
[currentNodeContent release];
currentNodeContent = nil;
}
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(#"found characters: %#", string);
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (void) dealloc
{
[parser release];
[super dealloc];
}
#end
I have already checked SO for answers and found a couple of similar posts, but nothing that gave a clear solution to this problem.
Can anyone shed some light on this problem? :) Any help is much appreciated!
your parser:foundCharacters: method does not work as it should.
This is from the NSXMLParserDelegate Protocol Reference
The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element. Because string may be only part of the total character content for the current element, you should append it to the current accumulation of characters until the element changes.
you could try something like this (ARC):
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(#"found characters: %#", string);
if (!currentNodeContent) {
currentNodeContent = [[NSMutableString alloc] init];
}
[currentNodeContent appendString:string];
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
// your code here
// when you are done with the string:
currentNodeContent = nil;
}

Adding objects to an NSMutableArray, order seems odd when parsing from an XML file

I am parsing an XML file for two elements: "title" and "noType". Once these are parsed, I am adding them to an object called aMaster, an instance of my own Master class that contains NSString variables.
I am then adding these instances to an NSMutableArray on a singleton, in order to call them elsewhere in the program. The problem is that when I call them, they don't seem to be on the same NSMutableArray index... each index contains either the title OR the noType element, when it should be both... can anyone see what I may be doing wrong? Below is the code for the parser. Thanks so much!!
#import "XMLParser.h"
#import "Values.h"
#import "Listing.h"
#import "Master.h"
#implementation XMLParser
#synthesize sharedSingleton, aMaster;
- (XMLParser *) initXMLParser {
[super init];
sharedSingleton = [Values sharedValues];
aMaster = [[Master init] alloc];
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
aMaster = [[Master alloc] init];
//Extract the attribute here.
if ([elementName isEqualToString:#"intro"]) {
aMaster.intro = [attributeDict objectForKey:#"enabled"];
} else if ([elementName isEqualToString:#"item"]) {
aMaster.item_type = [attributeDict objectForKey:#"type"];
//NSLog(#"Did find item with type %#", [attributeDict objectForKey:#"type"]);
//NSLog(#"Reading id value :%#", aMaster.item_type);
} else {
//NSLog(#"No known elements");
}
//NSLog(#"Processing Element: %#", elementName); //HERE
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else {
[currentElementValue appendString:string];//[tempString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
CFStringTrimWhitespace((CFMutableStringRef)currentElementValue);
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"item"]) {
[sharedSingleton.master addObject:aMaster];
NSLog(#"Added %# and %# to the shared singleton", aMaster.title, aMaster.noType); //Only having one at a time added... don't know why
[aMaster release];
aMaster = nil;
} else if ([elementName isEqualToString:#"title"]) {
[aMaster setValue:currentElementValue forKey:#"title"];
} else if ([elementName isEqualToString:#"noType"]) {
[aMaster setValue:currentElementValue forKey:#"noType"];
//NSLog(#"%# should load into the singleton", aMaster.noType);
}
NSLog(#"delimiter");
NSLog(#"%# should load into the singleton", aMaster.title);
NSLog(#"%# should load into the singleton", aMaster.noType);
[currentElementValue release];
currentElementValue = nil;
}
- (void) dealloc {
[aMaster release];
[currentElementValue release];
[super dealloc];
}
#end
Every time that didStartElement is called, you're setting aMaster to a new instance of the Master class. Based on the implementation of didEndElement, it looks like you should only be creating a new instance whenever a new item tag is found. This could be why each entry in the array has one value or the other, since a new instance is created for each value.

XML Parsing in Cocoa Touch/iPhone

Okay i have seen TouchXML, parseXML, NSXMLDocument, NSXMLParser but i am really confused with what to to do.
I have an iphone app which connects to a servers, requests data and gets XML response. Sample xml response to different set of queries is give at http://pastebin.com/f681c4b04
I have another classes which acts as Controller (As in MVC, to do the logic of fetch the data). This class gets the input from the View classes and processes it e.g. send a request to the webserver, gets xml, parses xml, populates its variables (its a singleton/shared Classes), and then responses as true or false to the caller. Caller, based on response given by the controller class, checks controller's variables and shows appropriate contents to the user.
I have the following Controller Class variables:
#interface backendController : NSObject {
NSMutableDictionary *searchResults, *plantInfoResults, *bookmarkList, *userLoginResult;
}
and functions like getBookmarkList, getPlantInfo. Right now i am printing plain XML return by the webserver by
NSLog(#"Result: :%#" [NSString stringWithContentsOfURL:url])
I want a generic function which gets the XML returned from the server, parseses it, makes a NSMutableDictionary of it containing XML opening tags' text representation as Keys and XML Tag Values as Values and return that.
Only one question, how to do that?.
Have you tried any of the XML Parsers you mentioned? This is how they set the key value of a node name:
[aBook setValue:currentElementValue forKey:elementName];
P.S. Double check your XML though, seems you are missing a root node on some of your results. Unless you left it out for simplicity.
Take a look at w3schools XML tutorial, it should point you in the right direction for XML syntax.
Consider the following code snippet, that uses libxml2, Matt Gallagher's libxml2 wrappers and Ben Copsey's ASIHTTPRequest to parse an HTTP document.
To parse XML, use PerformXMLXPathQuery instead of the PerformHTTPXPathQuery I use in my example.
The nodes instance of type NSArray * will contain NSDictionary * objects that you can parse recursively to get the data you want.
Or, if you know the scheme of your XML document, you can write an XPath query to get you to a nodeContent or nodeAttribute value directly.
ASIHTTPRequest *request = [ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:#"http://stackoverflow.com/"];
[request start];
NSError *error = [request error];
if (!error) {
NSData *response = [request responseData];
NSLog(#"Root node: %#", [[self query:#"//" withResponse:response] description]);
}
else
#throw [NSException exceptionWithName:#"kHTTPRequestFailed" reason:#"Request failed!" userInfo:nil];
[request release];
...
- (id) query:(NSString *)xpathQuery withResponse:(NSData *)respData {
NSArray *nodes = PerformHTMLXPathQuery(respData, xpathQuery);
if (nodes != nil)
return nodes;
return nil;
}
providing you one simple example of parsing XML in Table, Hope it would help you.
//XMLViewController.h
#import <UIKit/UIKit.h>
#interface TestXMLViewController : UIViewController<NSXMLParserDelegate,UITableViewDelegate,UITableViewDataSource>{
#private
NSXMLParser *xmlParser;
NSInteger depth;
NSMutableString *currentName;
NSString *currentElement;
NSMutableArray *data;
}
#property (nonatomic, strong) IBOutlet UITableView *tableView;
-(void)start;
#end
//TestXMLViewController.m
#import "TestXmlDetail.h"
#import "TestXMLViewController.h"
#interface TestXMLViewController ()
- (void)showCurrentDepth;
#end
#implementation TestXMLViewController
#synthesize tableView;
- (void)start
{
NSString *xml = #"<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Node><name>Main</name><Node><name>first row</name></Node><Node><name>second row</name></Node><Node><name>third row</name></Node></Node>";
xmlParser = [[NSXMLParser alloc] initWithData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
[xmlParser setDelegate:self];
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser setShouldResolveExternalEntities:NO];
[xmlParser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(#"Document started");
depth = 0;
currentElement = nil;
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSLog(#"Error: %#", [parseError localizedDescription]);
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
currentElement = [elementName copy];
if ([currentElement isEqualToString:#"Node"])
{
++depth;
[self showCurrentDepth];
}
else if ([currentElement isEqualToString:#"name"])
{
currentName = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"Node"])
{
--depth;
[self showCurrentDepth];
}
else if ([elementName isEqualToString:#"name"])
{
if (depth == 1)
{
NSLog(#"Outer name tag: %#", currentName);
}
else
{
NSLog(#"Inner name tag: %#", currentName);
[data addObject:currentName];
}
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([currentElement isEqualToString:#"name"])
{
[currentName appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"Document finished", nil);
}
- (void)showCurrentDepth
{
NSLog(#"Current depth: %d", depth);
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
data = [[NSMutableArray alloc]init ];
[self start];
self.title=#"XML parsing";
NSLog(#"string is %#",data);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
`enter code here`return [data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [data objectAtIndex:indexPath.row];
return cell;
}
#end