2012-05-08 103 views
4

我在RESTKit的潛力上銷售 - 聽起來很棒。使用RESTKit解析深層XML結構

不幸的是,我所能找到的所有例子都是圍繞解析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> 

比方說,我想擺脫這種飛對象的列表:

@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'鍵路徑,但我找不到任何類似的例子來模擬解決方案。 HALP?

+0

謝謝。你拯救我的一天:) – slobodans

回答

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