如何访问节点GDataXML中的节点

时间:2011-09-13 07:48:27

标签: iphone xml parsing gdataxml

下面是一些示例XML,显示了我尝试解析的基本设置。

到目前为止,我可以轻松地提取任务,任务,标题,提示,练习和文本的数据,以及在练习中抓取属性type

然而,我不能为我的生活弄清楚如何获得包含标签问题的问题块。

<?xml version="1.0" encoding="UTF-8" ?>
<tasks>
    <task>
    <title>Any ole text goes here</title>
    <hint>dont cross busy roads!</hint>
    <exercise type="yes_no">
            <text>which planet is nearest the sun?</text>
            <questions>
                    <question answer="false">Mars</question>
                    <question answer="true">Mercury</question>
                    <question answer="false">Saturn</question>
            </questions>
    </exercise>
</tasks>

以下是我到目前为止的数据:

-(void)createTask
{   
    self.task = [[Task alloc] init];

    // grab the task from the loaded xml
    NSArray *tasks = [[AppData sharedInstance].XMLTaskDocument.rootElement elementsForName:@"task"];

    // cycle through the task and extract its data assigning to appropriate model property
    for (GDataXMLElement *task in tasks )
    {   
        NSString *title = nil;
        NSArray *titles = [task elementsForName:@"title"];

        if ([titles count] > 0)
        {   
            GDataXMLElement *firstTitle = (GDataXMLElement *)[titles objectAtIndex:0];      
            title = firstTitle.stringValue; 
        } else continue;

        NSString *hint = nil;
        NSArray *hints = [task elementsForName:@"hint"];

        if ([hints count] > 0)
        {
            GDataXMLElement *firstHint = (GDataXMLElement *)[hints objectAtIndex:0];
            hint = firstHint.stringValue;   
        } else continue;


        NSString *type = nil;
        NSString *text = nil;
        NSArray *exercises = [task elementsForName:@"exercise"];

        if ([exercises count] > 0)
        {
            type = [(GDataXMLNode *)[[exercises objectAtIndex:0] attributeForName:@"type"] stringValue];

            GDataXMLElement *firstText = (GDataXMLElement *)[exercises objectAtIndex:0];
            text = firstText.stringValue;

            // THIS DOES NOT WORK :-(       
            NSArray *questions = [task elementsForName:@"questions"];
            if ([questions count] > 0)
            {
                NSLog(@"questions count is: %d", [questions count]);
            }   
        } else continue;
    }
}

有谁能告诉我如何抓住问题?

1 个答案:

答案 0 :(得分:3)

你犯了一个小错误。你从任务根调用'elementsForName:@“问题”,而不是从运动根调用。它不起作用,因为“question”元素不存在于task元素中,而只存在于exercise元素中。

解决方案看起来应该是这样的:

// Replace this
NSArray *questions = [task elementsForName:@"questions"];
if ([questions count] > 0)
{
        NSLog(@"questions count is: %d", [questions count]);
}

// By this
NSArray *questions = [[exercises objectAtIndex:0] elementsForName:@"questions"];
if ([questions count] > 0)
{
        NSLog(@"questions count is: %d", [questions count]);
}

我希望它会对你有所帮助。