我有一个包含以下信息的 xml 文件。
<?xml version="1.0"?>
-<Party>
-<Player>
<Name>Butch</Name>
<Level>1</Level>
<Class>Fighter</Class>
</Player>
-<Player>
<Name>Shadow</Name>
<Level>2</Level>
<Class>Rogue</Class>
</Player>
-<Player>
<Name>Crak</Name>
<Level>3</Level>
<Class>Wizard</Class>
</Player>
</Party>
我尝试通过执行以下操作将其添加到 NSMutableArray。
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Party" ofType:@"xml"];
NSData *xmlData = [[NSMutableArray alloc] initWithContentsOfFile:filePAth];
当我运行它时,我的数组对象中没有数据。
如果我将该行替换为;
NSdata *xmlData = [NSdata dataWithContentsOfFole:filePath];
它会加载我的数据,但不是我需要的格式。
我对 Objective-c 和 iPhone 开发非常陌生,任何帮助都将不胜感激。如果需要更多信息,我很乐意提供。
编辑 - 我正在使用 GDataXML 解析我的 xml
编辑 - 我的 Parser 类如下
@implementation PartyParser
+(NSString *)dataFilePath:(BOOL)forSave{
return [[NSBundle mainBundle] pathForResource:@"Party" ofType:@"xml"];
}
+(Party *)loadParty{
NSString *filePath = [self dataFilePath:FALSE];
//NSData *xmlData = [NSData dataWithContentsOfFile:filePath];
NSData *xmlData = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if(doc ==nil){return nil;}
NSLog(@"%@", doc.rootElement);
Party *party = [[[Party alloc] init] autorelease];
NSArray *partyMembers = [doc.rootElement elementsForName:@"Player"];
for (GDataXMLElement *partyMember in partyMembers)
{
NSString *name;
int level;
RPGClass rpgClass;
//Name
NSArray *names = [partyMember elementsForName:@"name"];
if(names.count > 0)
{
GDataXMLElement *firstName = (GDataXMLElement *) [names objectAtIndex:0];
name = firstName.stringValue;
}else continue;
//Level
NSArray *levels = [partyMember elementsForName:@"level"];
if(levels.count > 0)
{
GDataXMLElement *firstLevel = (GDataXMLElement *) [levels objectAtIndex:0];
level = firstLevel.stringValue.intValue;
}else continue;
//Class
NSArray *classes = [partyMember elementsForName:@"class"];
if(classes.count > 0)
{
GDataXMLElement *firstClass = (GDataXMLElement *) [classes objectAtIndex:0];
if([firstClass.stringValue caseInsensitiveCompare:@"fighter"] == NSOrderedSame)
{
rpgClass = RPGClassFighter;
}
else if([firstClass.stringValue caseInsensitiveCompare:@"rogue"] == NSOrderedSame)
{
rpgClass = RPGClassRogue;
}
else if([firstClass.stringValue caseInsensitiveCompare:@"wizard"] == NSOrderedSame)
{
rpgClass = RPGClassWizard;
}
else
{
continue;
}
}else continue;
Player *player = [[[Player alloc] initWithName:name level:level rpgClass:rpgClass] autorelease];
[party.players addObject:player];
}
//NSLog(@"%@", doc.rootElement);
//
[doc release];
[xmlData release];
return party;
}
@end