简体   繁体   English

Xcode中带有NSData的TBXML

[英]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: 我有一个返回漂亮平面XML文件的URL: <entries><title>val1</title><author>Bob</author></entries>该代码运行正常:

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). 它找到根元素,并调用valueOfAttribute:@“ title”,但该值始终为(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). 所以我的问题是:我是否需要做一些事情将NSData转换回可读的格式(我的印象是TBXML给出了使用NSData并进行计算的选项)。 If not, what is the call to create (and then use) an NSString in UTF8 from 'myData'? 如果不是,从“ myData”以UTF8创建(然后使用)NSString的调用是什么?

what is the call to create (and then use) an NSString in UTF8 from 'myData'? 从“ myData”以UTF8创建(然后使用)NSString的调用是什么?

use initWithData:encoding: 使用initWithData:encoding:

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

or stringWithUTF8String: if you know myData is null-terminated UTF8 string stringWithUTF8String:如果您知道myData是以Null结尾的UTF8字符串

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM