解析xml时如何选择两个同名元素 [英] How to choose between two elements of the same name when parsing xml

查看:55
本文介绍了解析xml时如何选择两个同名元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学校致力于解析 xml,我正在使用 Twitter 的 API.我试图获取推文的发布日期,但我遇到了一个问题:在 xml 中有两个具有相同名称的元素包含不同的值.然而,一个比另一个嵌套得更深,所以从逻辑上讲,我想检查嵌套的那个.我该怎么做?

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.

这是我正在调用的 didEndElement 方法的示例.

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

谢谢各位

推荐答案

添加代码以检查所需的嵌套日期元素的父标记.当您遇到开始标记时,请在您的代码中设置一个标志.现在,当您遇到日期标签时,请检查该标志是否已设置.如果未设置标志,则忽略日期标记.当您检测到父级的结束标记时,重置标志.

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.

这篇关于解析xml时如何选择两个同名元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆