Re: NSXMLNode and NSXMLElement
Re: NSXMLNode and NSXMLElement
- Subject: Re: NSXMLNode and NSXMLElement
- From: email@hidden
- Date: Wed, 21 Jan 2009 00:31:15 -0500
On Jan 20, 2009, at 10:33 PM, Martijn van Exel wrote:
Hi all,
Consider this small bit of (OpenStreetMap) XML:
<node id='257441001' lat='52.3506393' lon='4.8889186'
user='mvexel'
osmxapi:users='mvexel' timestamp='2008-12-11T13:11:41Z'>
<tag k='amenity' v='pub'/>
<tag k='name' v='Lust'/>
</node>
I got this (and its peers) in an array of NSXMLNodes using the
nodesForXPath
method on my NSXMLDocument object.
Now I need to get to the attribute KVPs. It seems that I must get the
individual nodes into NSXMLElement objects and then traverse the
array that
the attributes method of NSXMLElement yields. This somehow does not
feel
right. Is there a better way, given this bit of XML inside an
NSXMLNode, to
deserialize the attribute values in the different nodes?
KVC has a slick feature such that you can send valueForKey: or
valueForKeyPath: to an array and you will get back an array containing
the objects returned by sending the message to each member of the
array. In your case, if you send [nodes valueForKey:@"attributes"],
you will get a new array, but each member is now an array attributes
for the corresponding node in the original array. However, there
isn't a way to get the individual attributes using KVC. You could try
to work around this by using a category for NSXMLElement with a custom
valueForUndefinedKey:. For example:
@implementation NSXMLElement (Private)
- (id)valueForUndefinedKey:(NSString *)key
{
return [self attributeForName:key];
}
@end
I ran this in the debugger, where I had an array of two nodes like
your example:
(gdb) po [nodes valueForKey:@"lat"]
<NSCFArray 0x2188a0>(
lat="52.3506393",
lat="52.3506393"
)
Note that the members of the array are NSXMLNode objects of the
attribute kind (movie title???), so you still need to extract the
values, such as:
(gdb) po [nodes valueForKeyPath:@"lat.stringValue"]
<NSCFArray 0x217370>(
52.3506393,
52.3506393
)
Some might consider this an abuse of KVC, so I'm curious to hear
opinions...
Cheers,
Aaron Burghardt
email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden