Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone TBXML Looping And Parsing Data

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

<?xml version="1.0" encoding="UTF-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://schema.2sms.com/2.0/schema/0310_ResponseReportStandard.xsd" Version="1.0">
    <Error>
        <ErrorCode>00</ErrorCode>
        <ErrorReason>OK</ErrorReason>
    </Error>
    <ResponseData>
        <Identification>
            <UserID>[email protected]</UserID>
        </Identification>
        <Result>2 records were returned</Result>
        <Detail>
            <ReportTitle>Message Summary: Today</ReportTitle>
            <Record>
                <Destination>447790686158</Destination>
                <Status>WithNetwork</Status>
                <GUID><![CDATA[2011-03-22T10:54:22.097Z]]></GUID>
                <DateSubmitted>2011-03-22T10:54:22.097</DateSubmitted>
                <DateToSend></DateToSend>
                <DateSent>2011-03-22T10:54:22.533</DateSent>
                <DateReceived></DateReceived>
                <Message><![CDATA[Yet again another test]]></Message>
                <ID>2011-03-22 10:54:22.250HIHIIOJTFVETW85TS</ID>
            </Record>
            <Record>
                <Destination>447790686158</Destination>
                <Status>SUCCESS</Status>
                <GUID><![CDATA[2011-03-22T10:50:40.064Z]]></GUID>
                <DateSubmitted>2011-03-22T10:50:40.063</DateSubmitted>
                <DateToSend></DateToSend>
                <DateSent>2011-03-22T10:50:42.473</DateSent>
                <DateReceived>2011-03-22T10:50:54.570</DateReceived>
                <Message><![CDATA[This is a test]]></Message>
                <ID>2011-03-22 10:50:40.210DRUDVMCEZGETW85TS</ID>
            </Record>
            <ReportPage ReportID="775797" ItemsPerPage="25" Page="1" TotalItems="2" />
        </Detail>
    </ResponseData>
</Response>

I need those 2 <records> and all there data to be stored in an array. so....

an records array -> array of records -> array of each records, data....

I have been sitting here trying to work this out using TBXML which is easy enough to grab a single node.... but I can't do this :(

like image 569
MrPink Avatar asked Mar 23 '11 14:03

MrPink


2 Answers

Alright, your first step would be to make a class that will parse the data. Call it RecordParser, for example. We now need to add a couple methods in the header, as well as a NSMutableArray.

@interface RecordParser : NSObject {
    NSMutableArray *records;    
}
@property(nonatomic,retain)NSMutableArray *records;

-(void)loadRecords:(NSString *)records;
-(void)traverseElement:(TBXMLElement *)element;

@end

Now, go ahead and charge into your implementation. We now need to implement those two methods to do what we want them to do.

- (void)loadRecords:(NSString *)records {
    NSString *someXML = @"http://www.something.com/somexml.xml";
    TBXML *tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:someXML]] retain];

    records = [NSMutableArray array];
    [records retain];

    if (tbxml.rootXMLElement)
        [self traverseElement:tbxml.rootXMLElement];
    [tbxml release];
}

Basically that method will grab the XML file in question and begin the parsing process. Also, you're initializing your array and retaining it. Now we come to the cheese.

- (void) traverseElement:(TBXMLElement *)element {
    do {
        if (element->firstChild) 
            [self traverseElement:element->firstChild];

        if ([[TBXML elementName:element] isEqualToString:@"Record"]) {
            TBXMLElement *destination = [TBXML childElementNamed:@"Destination" parentElement:element];
            TBXMLElement *status = [TBXML childElementNamed:@"Status" parentElement:element];
            TBXMLElement *guid = [TBXML childElementNamed:@"GUID" parentElement:element];
            TBXMLElement *dateSub = [TBXML childElementNamed:@"DateSubmitted" parentElement:element];
            TBXMLElement *dateToSend = [TBXML childElementNamed:@"DateToSend" parentElement:element];
            TBXMLElement *dateSent = [TBXML childElementNamed:@"DateSent" parentElement:element];
            TBXMLElement *dateReceived = [TBXML childElementNamed:@"DateReceived" parentElement:element];
            TBXMLElement *message = [TBXML childElementNamed:@"Message" parentElement:element];
            TBXMLElement *id = [TBXML childElementNamed:@"ID" parentElement:element];

            [records addObject:[NSArray arrayWithObjects:
                                  [TBXML textForElement:destination],
                                  [TBXML textForElement:status],
                                  [TBXML textForElement:guid],
                                  [TBXML textForElement:dateSub],
                                  [TBXML textForElement:dateToSend],
                                  [TBXML textForElement:dateSent],
                                  [TBXML textForElement:dateReceived],
                                  [TBXML textForElement:message],
                                  [TBXML textForElement:id],nil]];  
        }
    } while ((element = element->nextSibling));  
}

Basically what the method does is transverse the XML file looking for an element with the name you're looking for, then it grabs the data from the child nodes. Additionally, the data is added to the records array. So basically, when it's done it should have the data you're wanting in your records array, which you can manipulate all you want.

This is completely untested. Don't blame me if it blows up your computer and kills your cat. I normally wouldn't take all the work to write a complete method like this, but I happen to like TBXML. Please let me know if it works. I really would appreciate knowing.

like image 62
sudo rm -rf Avatar answered Sep 28 '22 12:09

sudo rm -rf


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;
    }
like image 27
Nikolay Shubenkov Avatar answered Sep 28 '22 13:09

Nikolay Shubenkov