KissXML not returning strings

2019-05-22 14:22发布

问题:

I have an example XML like this:

<rss version="2.0"> 
<channel>
     <title></title>
     <link></link>
     <description></description>
<item>
   <title></title>
   <link></link>
   <description></description>
   <pubDate></pubDate>
   <guid></guid>
</item>

and so on… And my obj-c syntax is looking like this:

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];
}

It's returning no value, can anyone say me why?

回答1:

The problem is in this line:

 NSString *itemValueAsString = [[itemElement attributeForName:@"link"]stringValue];

link is not an attribute, but rather an element. So try this:

 NSString *itemValueAsString = [[[itemElement elementsForName:@"link"] lastObject] stringValue];


回答2:

For Swift 3,

let object: DDXMLElement = element.elements(forName: "objectKey").first!
yourModelClass.stringVariable = object.stringValue!


回答3:

NSArray *xmlItems = [[ddDoc rootElement] elementsForName:@"item"];