Parse XML From Wikipedia
-
01-07-2021 - |
Pregunta
I'm using NSXmlParser
and trying to parse this XML file:
<api>
<query>
<normalized>
<n from="new york" to="New york"/>
</normalized>
<redirects>
<r from="New york" to="New York"/>
</redirects>
<pages>
<page pageid="8210131" ns="0" title="New York">
<extract xml:space="preserve"><p><b>New York< ...
Basically this file is pretty long but I am trying to copy only the <extract>
element.
I have done it by several way with NSMutableString
with this code:
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
CrrentString = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[CrrentString appendString:string];
NSLog(@"%@",CrrentString);
}
-(void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
currentKey = nil;
if ([elementName isEqualToString:@"extract"]) {
CrrentString = [attributeDict objectForKey:@"extract"];
return;
}
}
But in the end, this gives me only >
inside the NSMutableString
(CrrentString
).
Solución
This line makes the issue:
CrrentString = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Each time when the found character method works it overwrites the previous CrrentString
. That's why you are getting the last found character only.
So change it like:
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSString *temp= (NSString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[CrrentString appendString:temp];
NSLog(@"%@",CrrentString);
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
CrrentString = nil;
if ([elementName isEqualToString:@"extract"])
{
CrrentString = [[NSMutableString alloc] init];
}
}
Hope it'll help.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow