2012-01-11 13 views
5

Ho letto molti esempi su come ottenere il testo dai file xml, ma non capisco come. Ecco un file XML di esempio:Analisi xml in NSXMLParser

<?xml version="1.0" encoding="UTF-8"?> 
<questions> 
    <set> 
     <question>Question</question> 
     <answer>Answer</answer> 
    </set> 
</questions> 

Utilizzando -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI, qual è il modo più semplice per ottenere i valori Question e Answer? Ho già il mio delegato del parser collegato e tutto quel blah.

risposta

13

Per attuare NSXMLParser è necessario implementare metodo delegato di esso.

Prima di tutto avviare NSXMLParser in questo modo.

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    rssOutputData = [[NSMutableArray alloc]init]; 

    //declare the object of allocated variable 
    NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@""]];// URL that given to parse. 

    //allocate memory for parser as well as 
    xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData]; 
    [xmlParserObject setDelegate:self]; 

    //asking the xmlparser object to beggin with its parsing 
    [xmlParserObject parse]; 

    //releasing the object of NSData as a part of memory management 
    [xmlData release]; 

} 
//------------------------------------------------------------- 


-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName 
    attributes: (NSDictionary *)attributeDict 
{ 
    if([elementName isEqualToString:@"question"]) 
    { 

     strquestion = [[NSMutableString alloc] init]; 

    } 
} 


//------------------------------------------------------------- 


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{ 
     // init the ad hoc string with the value  
    currentElementValue = [[NSMutableString alloc] initWithString:string]; 
    } else { 
    // append value to the ad hoc string  
    [currentElementValue appendString:string]; 
    } 
    NSLog(@"Processing value for : %@", string); 
} 


//------------------------------------------------------------- 


-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{ 
    if([elementName isEqualToString:@"question"]) 
    { 
     [strquestion setString:elementName]; 
    } 

[currentElementValue release]; 
    currentElementValue = nil; 
} 

Il metodo delegato sopra viene inviato da un oggetto parser al suo delegato quando incontra un fine specifico elemento. Con questo metodo didEndElement otterrete il valore di question.

+1

Una condizione if viene omessa in 'foundCharacters' :)' if (currentElementValue == nil) ' – GoodSp33d

+0

Qualcuno ha utilizzato questo codice recentemente? Sto ottenendo errori di "uso di identificatori non dichiarati xmlParserObject". C'è un'importazione mancante? – user3741598

+0

@ user3741598 basta fare NSXMLParser * xmlParserObject. Penso che nel codice di esempio sopra il parser sia dichiarato prima nell'intestazione, quindi non ha bisogno di dire il suo tipo. Questa è la mia ipotesi, almeno. –

2

è necessario implementare le funzioni di callback per NSXMLParserDelegate

Quelli principali sono:

// called when it found an element - in your example, question or answer 
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 

// called when it hits the closing of the element (question or answer) 
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 

// called when it found the characters in the data of the element 
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 

Così, quando si colpisce gli elementi, è possibile impostare lo stato se il parser è attualmente nella domanda o risposta elemento (con un iVar) e poi quando viene richiamato con foundCharacters, in base allo stato impostato quando si preme l'elemento, si conosce la variabile (domanda o risposta) a cui assegnare i dati.

2

è necessario implementare il metodo

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

Una volta che vedete gli elementi la cui (interno) il testo che si desidera afferrare, impostare un flag nel programma, e mantenere una stringa con le cose che foundCharacters reperti tra i tag. Una volta che si preme il metodo didEndElement, è possibile eseguire ciò che si desidera con la stringa e reimpostare il flag.

Per esempio

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
    if (sawQuestion) { 
    // need to check here that self->myString has been initialized 
    [self->myString appendString:string]; 
} 
} 

e in didEndElement è possibile reimpostare il flag sawQuestion

3
// This one called out when it hit a starting tag on xml in your case <question> 

    BOOL got = FALSE; 

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI 

{ 

     if([elementName isEqualToString:@"question"]) 
     { 
     got = TRUE; 
     } 
} 

// This is third one to called out which gives the end tag of xml in your case </question> 


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



// This delegate is the second one to called out which gives the value of current read tag in xml 

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

    if(got) 
    { 
    NSLog(@"your desired tag value %@",string); 
    got = FALSE; 
    } 
}