我正在使用TBXML解析器,但遇到一些困難。解析XML時數組被覆蓋(Objective-C)
我使用以下代碼將產品對象中的數據添加到名爲laarzen的MutableArray。
- (void)loadURL {
// Load and parse an xml string
Products *product = [[Products alloc] init];
tbxml = [[TBXML alloc] initWithURL:[NSURL URLWithString:@"url..."]];
// If TBXML found a root node, process element and iterate all children
// Obtain root element
TBXMLElement * root = tbxml.rootXMLElement;
// if root element is valid
if (root) {
// search for the first category element within the root element's children
TBXMLElement * Category = [TBXML childElementNamed:@"Category" parentElement:root];
Products *product = [[Products alloc] init];
// if an author element was found
while (Category!= nil) {
// instantiate an author object
// get the name attribute from the author element
product.category = [TBXML valueOfAttributeNamed:@"DisplayName" forElement:Category];
// search the author's child elements for a book element
TBXMLElement *xmlProduct = [TBXML childElementNamed:@"Product" parentElement:Category];
int i;
i=0;
// if a book element was found
while (xmlProduct != nil) {
// extract the title attribute from the book element
product.productId = [TBXML valueOfAttributeNamed:@"Id" forElement:xmlProduct];
// extract the title attribute from the book element
NSString * price = [TBXML valueOfAttributeNamed:@"Price" forElement:xmlProduct];
// if we found a price
if (price != nil) {
// obtain the price from the book element
product.price = [NSNumber numberWithFloat:[price floatValue]];
}
// add the book object to the author's books array and release the resource
[laarzen addObject:product];
// find the next sibling element named "book"
xmlProduct = [TBXML nextSiblingNamed:@"Product" searchFromElement:xmlProduct];
}
// add our author object to the authors array and release the resource
// find the next sibling element named "author"
Category = [TBXML nextSiblingNamed:@"Category" searchFromElement:Category];
}
}
// release resources
[tbxml release];
[product release];
}
由於某種原因,從xml解析出的最後一個節點會覆蓋數組中的所有條目。即如果最後的價格是39,99,則陣列中的價格將是39,99。
在我的viewDidLoad我正在分配laarzen如下:
laarzen = [[NSMutableArray alloc] init];
在我的dealloc我又釋放出來。
在頭文件中我做了以下內容:
NSMutableArray *laarzen;
@property (nonatomic, retain) NSMutableArray *laarzen;
這可能會是一個記憶的問題,但我只是沒有看到它。
THNX!
哇,我覺得愚蠢......可能編碼爲長..在迭代中放置產品的分配,它的工作! Thnx男人! – Jos