簡體   English   中英

使用NSXml解析xml響應

[英]Parsing an xml response using NSXml

我試圖解析一個具有一個根元素和兩個具有相同名稱的子元素的xml。 但是,它們一直在連接在一起。 我怎樣才能解決這個問題? 到目前為止,這是我的代碼

--

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

    element = elementName;

    if([element isEqualToString:@"bustime-response"]){
        self.item = [[NSMutableDictionary alloc]init];
        self.direction =[[NSMutableString alloc]init];

    }

}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    if ([element isEqualToString:@"dir"]){
        string = [string stringByTrimmingCharactersInSet:[NSCharacterSet  whitespaceAndNewlineCharacterSet]];
        [self.direction appendString:string];
    }
}

試試這個對我有用:

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

    if ([element isEqualToString:@"bustime-response"])
    {
        elementFound = YES;

        if (self.item)
            self.item = nil;
        self.item = [[NSMutableDictionary alloc]init];
        if (self.direction)
            self.direction  = nil;
        self.direction =[[NSMutableString alloc]init];
    }
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (elementFound)
    {
        if ([element isEqualToString:@"dir"]){
            string = [string stringByTrimmingCharactersInSet:[NSCharacterSet  whitespaceAndNewlineCharacterSet]];
            [self.direction appendString:string];
        }
        //Add another if with the tag you want to retrieve the data from here
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([element isEqualToString:@"bustime-response"])
    {
        elementFound = NO;
        // self.receivedDataArray - main array to store all of your dictionary
        [self.receivedDataArray addObject: self.direction];
            [self.receivedDataArray addObject: self.item];
        self.direction = nil;
            self.item = nil;
    }
}

如您所見,您必須添加另一個BOOL變量elementFound和NSMutableArray receiveedDataArray來存儲所有數據。 試一試,讓我知道它對您有用。 請記住,添加NSLogs進行調試很好,這很有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM