2013-11-15 63 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