objective-ctbxml

TBXML with NSData in Xcode


I have a URL that returns a pretty flat XML file: <entries><title>val1</title><author>Bob</author></entries> The code runs ok:

NSString *urlString = [NSString stringWithFormat:@"http://www.somesite.php?qid=%d", __inum];
NSLog(@"urlString = %@", urlString);
NSURLResponse * response = nil;
NSError * error = nil;
NSURLRequest * urlRequest = [NSURLRequest requestWithURL: [NSURL URLWithString:urlString]];
NSData * myData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

NSLog(@"%@", myData);

TBXML *sourceXML = [[TBXML alloc] initWithXMLData:myData error:nil];

TBXMLElement *rootElement = sourceXML.rootXMLElement;

if (rootElement) {

    NSLog(@"Root element found...");

TBXMLElement *qaElement1 = [TBXML childElementNamed:@"title" parentElement:rootElement];
if (qaElement1) {
    NSString *idAttribute = [TBXML valueOfAttributeNamed:@"title" forElement:qaElement1];
    NSLog(@"Got to the 1st call for idAttribute... %@", idAttribute);
}
else { NSLog(@"There is no value for title..."); }

}

else { NSLog(@"Root element must be null..."); }

}

It finds the root element and gets to the call for valueOfAttribute:@"title" but the value is always (null).

So my question: do I have to do something to convert the NSData back to man readable (I was under the impression TBXML gave that option to work with the NSData and did the calculation). If not, what is the call to create (and then use) an NSString in UTF8 from 'myData'?


Solution

  • what is the call to create (and then use) an NSString in UTF8 from 'myData'?

    use initWithData:encoding:

    NSString *str = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
    

    or stringWithUTF8String: if you know myData is null-terminated UTF8 string

    NSString *str = [NSString stringWithUTF8String:[myData bytes]];
    

    Do not ignore error.

    NSError *error = nil;
    TBXML *sourceXML = [[TBXML alloc] initWithXMLData:myData error:&error];
    if (error) {
         // handle it, at least log it
    }