0

我正在尝试获取根元素。基于根元素我想触发一个功能。

例如,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;

但它似乎跳过了根元素。我是否错过了任何可以首先获取根元素的方法?

4

1 回答 1

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;
    }
}

这是来自苹果的链接,请始终阅读文档及其代码示例... http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/NSXML_Concepts/NSXML.html#//apple_ref/文档/uid/TP40001263-SW1

我不是 100% 确定,但我认为它有效......

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

于 2012-12-10T15:41:44.637 回答