0

我正在尝试解析 XML 并将 XML 的一个元素中的 URL 存储到 NSArray 中。到目前为止,这是我的代码:

 NSURL *url = [NSURL URLWithString:@"http://www.316apps.com/LakesideDocs/podcasttrial.xml"];

   NSData *xmlData = [[NSMutableData alloc] initWithContentsOfURL:url];
   NSError *error;
   GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData 
                                                          options:0 error:&error];

   NSArray *channels = [doc.rootElement elementsForName:@"channel"];
   for (GDataXMLElement *channel in channels) {            


       NSArray *items = [channel elementsForName:@"item"];
       for (GDataXMLElement *item in items) {

           NSString *articlePoint = [item valueForChild:@"link"];
           NSArray *linkarray = [[NSArray alloc] initWithObjects:articlePoint, nil];

           NSLog(@"%@", linkarray);

       }

   }

对于 NSLog 我希望:

TabBarSample[40191:fb03] (
    (
    "http://domain.com/image1.jpg"
 ),
(
"http://domain.com/image2.jpg"
)
)

但我得到:

TabBarSample[40191:fb03] (
"http://domain.com/image1.jpg"
)
TabBarSample[40191:fb03] (
"http://domain.com/image2.jpg"
)

我究竟做错了什么?

4

1 回答 1

2

每个循环都创建一个新数组:

 NSArray *linkarray = [[NSArray alloc] initWithObjects:articlePoint, nil];

相反,您希望在 llop 之外有一个 NSMutableArray 并在每个循环期间添加一个对象

   NSMutableArray *linkarray = [NSMutableArray array];
   NSArray *items = [channel elementsForName:@"item"];
   for (GDataXMLElement *item in items) {

       NSString *articlePoint = [item valueForChild:@"link"];
       [linkarray addObject:articlePoint];

       NSLog(@"%@", linkarray);

   }

如果增加的数组让您感到困惑,您应该将 NSLog 放在 for 循环之后:

   NSMutableArray *linkarray = [NSMutableArray array];
   NSArray *items = [channel elementsForName:@"item"];
   for (GDataXMLElement *item in items) {

       NSString *articlePoint = [item valueForChild:@"link"];
       [linkarray addObject:articlePoint];
   }

   NSLog(@"%@", linkarray);
   NSLog(@"count: %d", [linkarray count]);
于 2012-05-23T19:51:50.790 回答