在目标c中访问属性的xml解析

时间:2013-03-27 21:48:23

标签: objective-c xml parsing

我正在尝试解析xml文件,但我无法检索其中的所有对象。

我的xml是

<exam>
<question s="1" a="2" m="1"  x="1">
    <q>question</q>
    <o p="">question</o>
    <o p="">question</o>
    <o p="">question</o>
    <o p="">question</o>

</question>
<question s="2" a="1,3,5" m="3" p="1.2.jpg" x="1">
    <q>question</q>
    <o p="">question</o>
    <o p="">question</o>
    <o p="">question</o>
    <o p="">question</o>
    <o p="">question</o>
    <o p="">question</o>
</question>
</exam>

如何检索所有数据,例如“s =”2“”和“&lt; .o p =&gt; question&lt; ./ o&gt;”

2 个答案:

答案 0 :(得分:0)

使用GDataXML&amp;考虑xmlData将是XML字符串NSData表示。

GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData error:&error];

NSArray *dataArray = [doc nodesForXPath:@"//exam/question" error:nil];

  for (GDataXMLElement *element in dataArray) {

        NSArray * question = [element elementsForName:@"s"];

        if (question.count > 0) {
            GDataXMLElement *questionElement = (GDataXMLElement *) [question objectAtIndex:0];
            questionString = [questionElement stringValue];
        }
}

查看更多详情here

答案 1 :(得分:0)

感谢您的帮助。这是我在朋友的帮助下找到的解决方案(对于选择不当的变量名称感到抱歉):

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    currentElement = elementName;
    if([elementName isEqualToString:@"item"])
    {
        qes = [[Qes alloc] init];
        qes.s= [attributeDict objectForKey:@"s"];

    }

}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if([currentElement isEqualToString:@"q"])
        [qes.question appendString:string];
    if([currentElement isEqualToString:@"o"])
    {
        [qes.answers addObject:string];
    }

}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if([elementName isEqualToString:@"item"])
    {
        [quests addObject:qes];

    }
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
    for (Qes *s in quests) {
        NSLog(s.question);
        NSLog(@"s-----");
        NSLog(s.s);

        for (NSString *w in s.answers) {
             NSLog(w);

        }

    }

}