iPhone TBXML Looping And Parsing Data

后端 未结 4 1581
春和景丽
春和景丽 2020-12-18 00:12

Basically I have an XML response that is returned and a string, and i need to loops through the xml and store all the information in an array. here is the xml



        
4条回答
  •  Happy的楠姐
    2020-12-18 01:09

    I wrote recursive function to parse any properly created xml with TBXML library.

    In my project I have a class to parse XML. It has a Class Method named: + (id) infoOfElement: (TBXMLElement*) element

    How to use:

    TBXML *tbxml = [TBXML tbxmlWithXMLData:yourData];
    TBXMLElement *rootXMLElement = tbxml.rootXMLElement;
    
    id parsedData = [self infoOfElement: rootXMLElement];
    
        //return NSString or NSDictionary ot NSArray of parsed data
        + (id) infoOfElement: (TBXMLElement*) element
        {
            if (element->text)
                return [TBXML textForElement:element];
            NSMutableDictionary *info = [NSMutableDictionary new];
            TBXMLAttribute *attribute = element->firstAttribute;
            if (attribute) {
                do {
                    [info setValue:[TBXML attributeValue:attribute] forKey:[TBXML attributeName:attribute]];
                    attribute = attribute -> next;
                } while (attribute);
            }
            TBXMLElement *child = element->firstChild;
            if (child){
                TBXMLElement *siblingOfChild = child->nextSibling;
                //If we have array of children with equal name -> create array of this elements
                if ([[TBXML elementName:siblingOfChild] isEqualToString:[TBXML elementName:child]]){
                    NSMutableArray *children = [NSMutableArray new];
                    do {
                        [children addObject:[self infoOfElement:child]];
                        child = child -> nextSibling;
                    } while (child);
                    return [NSDictionary dictionaryWithObject:children forKey:[TBXML elementName:element]];
                }
                else{
                    do {
                        [info setValue:[self infoOfElement:child] forKey:[TBXML elementName:child]];
                        child = child -> nextSibling;
                    } while (child);
                }
            }            
            return info;
        }
    

提交回复
热议问题