开发者

Parsing Dates in XML for iOS SDK using TBXML

I'm using the TBXML parser. I'm not sure this is specific to TBXML or not. I have an XML file that has a date in. I'm then parsing this using TBXML. I then want to format this date using NSDateFormatter, however when I debug this and output using NSLog, it displays as (null).

Here is my XML:

<locations>
    <location>
        <place>null</place>
        <geo>null</geo>
        <location_date>2010-12-25 10:15:15 +0000</location_date>
    </location>
    <location>
        ...
    </location>
</locations>

This is how I'm parsing. I've loaded the XML file in ok (I've tested other nodes and I can output the values ok so it's reading the XML fine. I detect root and then do a while loop around the node. I have created a Location class that has the relevant properties to hold the retrieved XML node values. These are all NSString, however I did try NSDate for locationDate.

Should I be storing the date differently in the node? Happy to provide more code if need开发者_如何学JAVAed.

if (root) {
        // search for the first location element within the root element's children
        TBXMLElement * location = [TBXML childElementNamed:@"location" parentElement:root];
        NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMdd"];

        // if an location element was found
        while (location != nil) {

            // instantiate an location object
            Location * aLocation = [[Location alloc] init];

            TBXMLElement * locationDate = [TBXML childElementNamed:@"location_date" parentElement:location];

            // if we found a locationDate
            if (locationDate != nil) {
                aLocation.locationDate = [TBXML textForElement:locationDate];
                NSDate *locDate=[formatter dateFromString:aLocation.locationDate];
                NSLog(@"the current location date is %@", locDate);
            }

            [locations addObject:aLocation];
        [aLocation release];

            // find the next sibling element named "location"
            location = [TBXML nextSiblingNamed:@"location" searchFromElement:location];

        }
    }

The console output I get is:

the current location date is (null)

The idea would be to then put this in a format so I can compare the dates against now, however I can't even read the dates in from the xml and format them properly yet.

Any help is appreciated.

Paul


Your DateFormat is not correct. If it's not perfectly set up, the resulting string will be nil. Try it this way:

[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss +ZZZ"];

Check here for a nice reference for NSDateFormatter:

http://cocoawithlove.com/2009/05/simple-methods-for-date-formatting-and.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜