我有一个包含国家/地区和代码的xml文件。我把xml放在Demo.xml中。我的问题是只保存了第一个字典。或者任何人都可以告诉我解析它的其他方式,如使用nsxml或gdata
NSString *filePath=[[NSBundle mainBundle] pathForResource:@"Demo" ofType:@"xml"];
NSData *data=[NSData dataWithContentsOfFile:filePath];
addArray=[[NSMutableArray alloc]init];
dictData=[[NSMutableDictionary alloc]init];
TBXML *tbxml = [TBXML tbxmlWithXMLData: data];
TBXMLElement *rootXMLElement=tbxml.rootXMLElement;
TBXMLElement *rootElemnt=[TBXML childElementNamed:@"root" parentElement:rootXMLElement];
while (rootElemnt!=nil) {
TBXMLElement *item = [TBXML childElementNamed:@"item" parentElement:rootElemnt];
if (item!=nil) {
TBXMLElement *country = [TBXML childElementNamed:@"country" parentElement:item];
TBXMLElement *code = [TBXML childElementNamed:@"code" parentElement:item];
dictData=[NSMutableDictionary dictionaryWithObjectsAndKeys:[TBXML textForElement:country],@"country",[TBXML textForElement:code],@"code",nil];
rootElemnt = [TBXML nextSiblingNamed:@"item" searchFromElement:rootElemnt];
[addArray addObject:dictData];
}
}
NSLog(@"====%@",addArray);
outPut是:
====(
{
code = 355;
country = Albania;
}
)
的链接
答案 0 :(得分:2)
未经测试但
NSString *filePath=[[NSBundle mainBundle] pathForResource:@"Demo" ofType:@"xml"];
NSData *data=[NSData dataWithContentsOfFile:filePath];
addArray=[[NSMutableArray alloc]init];
dictData=[[NSMutableDictionary alloc]init];
TBXML *tbxml = [TBXML tbxmlWithXMLData: data];
TBXMLElement *rootXMLElement=tbxml.rootXMLElement;
TBXMLElement *rootElemnt=[TBXML childElementNamed:@"root" parentElement:rootXMLElement];
if (rootElemnt) {
TBXMLElement *item = [TBXML childElementNamed:@"item" parentElement:rootElemnt];
while (item) {
TBXMLElement *country = [TBXML childElementNamed:@"country" parentElement:item];
TBXMLElement *code = [TBXML childElementNamed:@"code" parentElement:item];
dictData=[NSMutableDictionary dictionaryWithObjectsAndKeys:[TBXML textForElement:country],@"country",[TBXML textForElement:code],@"code",nil];
[addArray addObject:dictData];
item = [TBXML nextSiblingNamed:@"item" searchFromElement:item];
}
}
NSLog(@"====%@",addArray);
应该有效