我有一个像这样的XML示例:
<rss version="2.0">
<channel>
<title></title>
<link></link>
<description></description>
<item>
<title></title>
<link></link>
<description></description>
<pubDate></pubDate>
<guid></guid>
</item>
等等......我的obj-c语法看起来像这样:
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
DDXMLDocument *ddDoc = [[DDXMLDocument alloc] initWithData:data options:0 error:&error];
NSArray *xmlItems = [ddDoc nodesForXPath:@"//item" error:&error]; // where ddDoc is your DDXMLDocument
NSMutableArray *returnArray = [[NSMutableArray alloc] initWithCapacity:[xmlItems count]];
for(DDXMLElement* itemElement in xmlItems)
{
ActiveActivity *activity = [[ActiveActivity alloc] init];
NSString *itemValueAsString = [[itemElement attributeForName:@"link"]stringValue];
[returnArray addObject:activity];
}
它没有返回任何价值,有人能说我为什么吗?
答案 0 :(得分:4)
问题出在这一行:
NSString *itemValueAsString = [[itemElement attributeForName:@"link"]stringValue];
link
不是属性,而是元素。所以试试这个:
NSString *itemValueAsString = [[[itemElement elementsForName:@"link"] lastObject] stringValue];
答案 1 :(得分:0)
对于Swift 3,
let object: DDXMLElement = element.elements(forName: "objectKey").first!
yourModelClass.stringVariable = object.stringValue!
答案 2 :(得分:-1)
NSArray *xmlItems = [[ddDoc rootElement] elementsForName:@"item"];