2013-11-15 216 views
1

我正在嘗試使用XPath選擇節點... 我使用以下代碼是我的iOS應用程序收集有關我擁有的書籍類型的一些信息,無論它們是平裝還是精裝:使用XPath選擇節點

nodes= [rootNode nodesForXpath:@"Collection/books" error:nil]; 
for (DDXMLNode* node in nodes) 
{ 
    Booktype* bt = [[Booktype alloc] init]; 
    DDXMLNode *nameNode = [[node nodesForXpath:@"OfType" error:nil]; objectAtIndex:0]; 
    bt.type = [nameNode stringValue]; 

    // And lastly, I am adding this object to my array that will be the datasource for my tableView 
    [array addObject:bt]; 
} 

我的圖書館XML看起來是這樣的:

<Collection> 

<books> 
    <title lang="eng">Harry Potter</title> 
    <price>29.99</price> 
    <ofType>Hardcover</ofType> 
</books> 

<books> 
    <title lang="eng">Stella Bain</title> 
    <price>19.99</price> 
    <ofType>Hardcover</ofType> 
</books> 

<books> 
    <title lang="eng">The First Phone Call from Heaven</title> 
    <price>12.95</price> 
    <ofType>Paperback</ofType> 
</books> 

<books> 
    <title lang="eng">Learning XML</title> 
    <price>39.95</price> 
    <ofType>Paperback</ofType> 
</books> 

</Collection> 

所以我有2平裝本和精裝2本書籍:偉大。現在的問題是,當將數據加載到我的tableView爲我的ofType要求4分共發佈信息:

我得到類似如下的表格視圖:

enter image description here

我怎樣才能去只有一個類型的實例嗎?因此,而不是每個我只會得到1平裝上市和1精裝清單...我的意圖是稍後添加tableView將列出選定類型的書籍類別中的所有書籍。

請在您的答案中儘可能詳細和詳細。

問候, -VZM

更新:我試圖實現以下:

if (![array containsObject:bt]) { 
    [array addObject:bt]; 
} 

但不幸的是,這是返回相同的結果。

回答

0

您可以將您的Booktypearray像以前那樣簡單地檢查,

if (![array containsObject:bt]) { 
    [array addObject:bt]; 
} 
+0

我只是想實現這個代碼,但不幸的是它沒有工作......我得到了同樣的結果,當我發佈問題@Anusha – vzm

0

您需要使用NSPredicate這一點。

變化:

[array addObject:bt]; 

有了:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.type == %@", bt.type]; 
if ([[array filteredArrayUsingPredicate:predicate] count] == 0) 
{ 
    [array addObject:bt]; 
} 
0

我希望這會給出一個想法,你...

NSMutableArray *arrayPaperCover = [[NSMutableArray alloc]init]; 
    NSMutableArray *arrayHardCover = [[NSMutableArray alloc]init]; 

    nodes= [rootNode nodesForXpath:@"Collection/books" error:nil]; 
    for (DDXMLNode* node in nodes) 
    { 
     Booktype* bt = [[Booktype alloc] init]; 
     DDXMLNode *nameNode = [[node nodesForXpath:@"OfType" error:nil] objectAtIndex:0]; 
     bt.type = [nameNode stringValue]; 


     if ([bt.type isEqualToString:@"Paperback"]) { 
      [arrayPaperCover addObject:bt]; 

     } 
     else ([bt.type isEqualToString:@"Hardcover"]) { 
      [arrayHardCover addObject:bt]; 

     } 

    } 
    NSMutableArray * dataSource = [[NSMutableArray alloc]init]; // this will be your data source 
    [dataSource addObject:arrayPaperCover]; 
    [dataSource addObject:arrayHardCover]; 
+0

懷疑ping我 – Spynet