加载XML文档
问题描述:
可能是一个简单的问题,但我不是加载文件的好...加载XML文档
让我的脚湿处理XML文档,我试图加载XML记录并在控制台中显示其节点的内容。这里是我的代码:
// AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *doc = [mainBundle pathForResource:@"helloworld" ofType:@"musicxml"];
[RootViewController testDoc:doc];
return YES;
}
// Implementation of testDoc: method
+ (void)testDoc:(NSString *)filePath {
NSError *err = nil;
DDXMLDocument *document = [[DDXMLDocument alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]] options:0 error:&err];
NSLog(@"filePath is %@", filePath);
NSLog(@"document is %@", document);
DDXMLNode *node = [document rootElement];
NSMutableString *xmlContent = nil;
while ((node = [node nextNode])) {
[xmlContent appendFormat:@"%@ ", [node stringValue]];
}
[xmlContent appendString:@"\n"];
NSLog(@"Test data is %@", xmlContent);
}
在控制台中,我看到路径格式正确;去Finder的那个位置确实会显示我正在寻找的文件。问题是document和xmlContent都打印出来(null)。我不太确定缺货情况在哪里发生......任何人都可以指出我正确的方向吗?
答
我不知道如果打印DDXMLDocument作为一个的NSLog%@会发生什么,但显示的XML结构做了
NSLog(@"%@", [document XMLStringWithOptions:DDXMLNodePrettyPrint]);
对于加载文档尝试:
DDXMLDocument *document = [[DDXMLDocument alloc] initWithData:[NSData dataWithContentsOfFile:filePath] options:0 error:&err];
xmlContent将输出为null,因为您没有分配NSMutableString的实例。 尝试设置
NSMutableString *xmlContent = [[[NSMutableString alloc] init] autorelease];