2011-03-19 112 views
0

我想解析xml文件,使用NSXMLParser。我的NSXMLParserDelegate實現了parser:didStartElementparser: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都是空的。

回答

0

要記錄NSStrings,請使用%@而不是%s。更改兩個NSLog行。請參閱String Format Specifiers瞭解使用說明符列表。

另一個問題是didEndElement委託方法沒有屬性參數,所以你寫的方法不會被調用。它應該是:

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
    namespaceURI:(NSString *)namespaceURI 
    qualifiedName:(NSString *)qualifiedName 
{ 
    NSLog(@"end: element %@ uri %@ qualified name %@", 
       elementName, namespaceURI, qualifiedName); 
} 
0
Try to compare with element name and get the results like the following 

if([elementName isEqualToString:@"component"]) 
{ 
//print something related to xml data 
} 

Use %@ instead of %s for printing. 
相關問題