How to choose between two elements of the same name when parsing xml

时间秒杀一切 提交于 2019-12-12 03:44:35

问题


I'm working on parsing xml in school, and I'm using Twitter's API to work with. I'm trying to grab the date the tweet was posted, but I'm running into an issue: there are two elements with the same name that hold different values inside of the xml. One is nested further in than the other, however, so logically I would want to check for the one that is nested. How would I go about doing that?

Everything is running perfectly right now. I just want to add more to my project.

Here's an example of the didEndElement method I'm calling.

 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:          (NSString *)namespaceURI qualifiedName:(NSString *)qName
{
//Creates an instance of the singleton to grab the array stored there
DataArraySingleton *singleton = [DataArraySingleton sharedArray];

//easy access to array
NSMutableArray *array = singleton.theArray;

//If the element ends with text
if ([elementName isEqualToString:@"text"])
{
    //Sets the value/key pair for text
    [tweets setValue:currentXMLValue forKey:elementName];

}
//Same as above
if ([elementName isEqualToString:@"screen_name"])
{
    [tweets setValue:currentXMLValue forKey:elementName];
}
//Same as above
if ([elementName isEqualToString:@"profile_image_url"])
{
    [tweets setValue:currentXMLValue forKey:elementName];
}
//If the element ends with status
if ([elementName isEqualToString:@"status"])
{
    //Adds the objects collected above to the array
    [array addObject:tweets];

    //Resets the object TweetInformation to be called again above
    tweets = nil;

}
//Resets xml value
currentXMLValue = nil;
}

Thanks guys


回答1:


Add code to check for the parent tag of the nested date element that you want. When you encounter the start tag, set a flag in your code. Now when you encounter the date tag, check if the flag is set or not. Ignore the date tag if the flag isn't set. When you detect the end tag for the parent, reset the flag.



来源:https://stackoverflow.com/questions/15058991/how-to-choose-between-two-elements-of-the-same-name-when-parsing-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!