2

下面是一些示例 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;
    }
}

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

4

1 回答 1

3

你犯了一个小错误。您从任务根而不是练习根调用“elementsForName:@"questions"'。它不起作用,因为“问题”元素不存在于任务元素中,而仅存在于练习元素中。

解决方案应如下所示:

// 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]);
}

我希望它会帮助你。

于 2011-09-13T10:01:01.927 回答