4

我被 RESTKit 的潜力所吸引——听起来很棒。

不幸的是,我能找到的所有示例都围绕解析 JSON,以及解析相对“扁平”的 JSON。世界上不幸的现实是,有很多 XML,而且很多都是丑陋的。

特别是,我似乎找不到任何解析深度嵌套 XML 结构的好例子。

我认为我的失败在于理解关键路径,我希望这个问题的答案将成为其他面临这个问题的人的典型例子。

让我们举一个人为的例子。考虑以下 XML:

<?xml version="1.0"?> 
<old_lady fate="perhaps she'll die!"> 
  <bird reason = "to catch the spider"> 
    <spider reason="to catch the fly"> 
      <fly reason="why oh why?" action="swallowed" name="Al"/> 
      <fly reason="why oh why?" action="swallowed" name="Bob"/> 
      <fly reason="why oh why?" action="swallowed" name="Cory"/> 
      <fly reason="why oh why?" action="swallowed" name="Dan"/> 
      <fly reason="why oh why?" action="swallowed" name="Edgar"/> 
    </spider> 
  </bird> 
</old_lady>

假设我想从中得到一个 Fly 对象列表:

@interface Fly : NSObject 
@property (retain) NSString *reason; 
@property (retain) NSString *action; 
@property (retain) NSString *name; 
@end 

所以我以为我会做这样的事情:

[RKObjectManager objectManagerWithBaseURL:[NSURL 
URLWithString:@"http://some.server.com"]];

RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Fly class]]; 
[mapping mapKeyPath:@"reason" toAttribute:@"reason"]; 
[mapping mapKeyPath:@"action" toAttribute:@"action"]; 
[mapping mapKeyPath:@"name" toAttribute:@"name"];

[RKObjectManager.sharedManager.mappingProvider setMapping:mapping
forKeyPath:@"//old_lady/bird/spider/fly"]; 

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/path/to/rhyme.xml" 
                                                  delegate:self]; 

然而,这让我:

Encountered errors during mapping: Could not find an object mapping for keyPath: '' 

我确定问题出在我的“//old_lady/bird/spider/fly”关键路径上,但我找不到任何类似的示例来模拟解决方案。哈普?

4

1 回答 1

9

我觉得自己像个傻瓜。在被困在这个问题上一天多之后,我在发布到 stackoverflow 后不久才发现了解决方案。

我的问题是我将 XPath 的概念与 Objective-C 的键值编码键路径的概念混淆了。

事实上,使用这个:

[RKObjectManager.sharedManager.mappingProvider setMapping:mapping 
forKeyPath:@"old_lady.bird.spider.fly"]; 

并因此记录结果:

- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects: 
(NSArray *)objects 
{ 
    for (Fly *fly in objects) 
    { 
        NSLog(@"%@, %@, %@", fly.reason, fly.action, fly.name); 
    } 
} 

正如预期的那样,我在控制台中看到了这一点:

2012-05-08 14:08:50.173 Foo[26922:207] why oh why?, swallowed, Al 
2012-05-08 14:08:50.173 Foo[26922:207] why oh why?, swallowed, Bob 
2012-05-08 14:08:50.175 Foo[26922:207] why oh why?, swallowed, Cory 
2012-05-08 14:08:50.176 Foo[26922:207] why oh why?, swallowed, Dan 
2012-05-08 14:08:50.176 Foo[26922:207] why oh why?, swallowed, Edgar 
于 2012-05-09T19:13:52.430 回答