我想解析xml文件,使用NSXMLParser
。我的NSXMLParserDelegate
實現了parser:didStartElement
和parser:didEndElement
,它從解析器獲取每個元素的消息。但是,當我嘗試打印它們時,我發現信息是空的。我錯過了什麼?使用NSXMLParser解析xml
我代表:
@interface ExtensionXML : NSObject <NSXMLParserDelegate> {
@private NSXMLParser* xmlParser;
@private NSURL* fileUrl;
}
- (void) parse;
- (ExtensionXML*) initWithPath: (NSString*)path;
@end
@implementation ExtensionXML
- (ExtensionXML*) initWithPath: (NSString*)path
{
if (self = [super init])
{
fileUrl = [NSURL fileURLWithPath:[path stringByExpandingTildeInPath]]; // error handling
}
return self;
}
- (void) parse
{
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:fileUrl];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser setShouldProcessNamespaces:YES];
[xmlParser setShouldReportNamespacePrefixes:YES];
[xmlParser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
NSLog(@"start: element %s uri %s qualified name %s", elementName, namespaceURI, qualifiedName);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
NSLog(@"end: element %s uri %s qualified name %s", elementName, namespaceURI, qualifiedName);
}
@end
XML文件是:
<someroot xmlns="http://ns.mycompany.com/product/format/1.3">
<id>myid</id>
<version>1</version>
<components>
<component name="componentOne">
<initializer>Init0</initializer>
</component>
</components>
</someroot>
輸出從NSLog
顯示的ElementName,則namespaceURI和qualifiesName都是空的。