Monday, January 09, 2012

iOS: XML

Download TBXML http://www.tbxml.co.uk

Add "libz.dylib" into project. Project > main directory > Build phases > link Binary with Libraries > "+" > iOS 5.0 - "libz.dylib" > Add

import "TBXML.h"


- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    UITextView *tv = [[UITextView alloc] initWithFrame:CGRectMake(5, 50, self.view.frame.size.width-10, 300)];
    [self.view addSubview:tv];
    
    // load xml file
    TBXML *fileRead = [[TBXML alloc] initWithXMLFile:@"properties.xml"];
    // get root element "list"
    TBXMLElement *root = fileRead.rootXMLElement;
    
    NSString *str = [[NSString alloc] init];
    
    if(root)
    {
        NSLog(@"has root");
        
        // get first "property" child element from root element
        TBXMLElement *property = [TBXML childElementNamed:@"property" parentElement:root];
        
        while(property)
        {
            NSString *name = [TBXML textForElement:[TBXML childElementNamed:@"name" parentElement:property]];
            NSLog(@"name: %@", name);
            NSString *price = [TBXML textForElement:[TBXML childElementNamed:@"price" parentElement:property]];
            NSString *propertyID = [TBXML valueOfAttributeNamed:@"id" forElement:property];
            NSLog(@"id: %@", propertyID);
            
            // use current element "property" to fetch the next sibling "property"
            property = [TBXML nextSiblingNamed:@"property" searchFromElement:property];
            
            // append to string
            str = [str stringByAppendingFormat:@"%@: %@, $%@\n", propertyID, name, price];
        }
        // show on textview
        [tv setText:str];
    }
    
}





No comments: