nsxmlparser读取根元素

时间:2012-12-10 15:31:16

标签: objective-c ios xcode nsxmlparser

我正在尝试获取根元素。基于我想要触发函数的根元素。

例如,xml看起来像这样:

  <State>
     <Name>California</Name>
     <Time>CA Time.</Time>
     <Time>CA Time2.</Time>
     <Notes>This is a note for California</Notes>
  </State>

,下一个传入的xml如下所示:

  <country>
     <Name>USA</Name>
     <Time>west coast Time.</Time>
  </country>

所以根据我要触发正确功能的根元素。我正在使用当前的NSXmlparser委托方法。

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;

但似乎它正在跳过根元素。我错过了任何可以先获得根元素的方法吗?

1 个答案:

答案 0 :(得分:4)

检查出来:

- (void)parser:(NSXMLParser *)parser 
didStartElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qName 
attributes:(NSDictionary *)attributeDict
{    
    currentKey = nil;
    [currentStringValue release];
    currentStringValue = nil;
    if([elementName isEqualToString:@"State"]){
       // Here you got the your root...
    }
}

- (void)parser:(NSXMLParser *)parser 
foundCharacters:(NSString *)string
{
    if(currentKey){
        if(!currentStringValue){ // Here you got the contents...
            // Store them somewhere in case you need them...
            currentStringValue = [[NSMutableString alloc] initWithCapacity:200];
        }
        [currentStringValue appendString:string];
    }
}

-(void)parser:(NSXMLParser *)parser 
didEndElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI 
qualifiedName:(NSString *)qName
{
    if([elementName isEqualToString:@"State"]){
        // Do what you want here...
        return;
    }
}

以下是来自apple的链接,请务必阅读文档及其代码示例... http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/NSXML_Concepts/NSXML.html#//apple_ref/doc/uid/TP40001263-SW1

我不是百分百肯定,但我认为它有效......

因此,您可以对县进行更改。