I'm trying to use XPath to parse an XML document. One of my NSXMLElement's looks like the following, hypothetically speaking:

<foo bar="yummy">

I'm trying to get the value for the attribute bar, however any interpretation of code I use, gives me back bar="woo", which means I need to do further string processing in order to obtain access to woo and woo alone.

Essentially I'm doing something like

NSArray *nodes = [xmlDoc nodesForXPath:@"foo/@bar" error:&error];
xmlElement = [nodes objectAtIndex:0];

Is there anyway to write the code above to just give me yummy, versus bar="yummy" so I can relieve myself of parsing the string?


Assuming TouchXML is being used, is there still anyway to obtain similar results? As in grabbing just the value for the attribute, without the attribute="value"? That results in then further having to parse the string to get the value out.

Was it helpful?


The TouchXML API is supposed to be an exact duplicate of Apple's NSXML implementation, so it should be the same except you'll replaces all NS-Method's with C-Methods.

The TouxhXML classes map directly to the NSXML classes. NSXMLNode -> CXMLNode, NSXMLDocument -> CXMLDocument, NSXMLElement -> CXMLElement. For obvious reasons you can't mix and match NSXML and TouchXML classes.

The TouxhXML methods map directly to NSXML methods as well, but only a small subset of methods are supported. Constant and enum names are almost equivalent (CXML... vs NSXML...) but constant values will not be equival


Using either the regular Apple classes or the TouchXML framework the following code will give you just the string "yummy" for your example.

 NSArray *nodes = [xmlDoc nodesForXPath:@"./foo/@bar" error:&err];
 NSString *value = [[nodes objectAtIndex:0] stringValue];

Good Luck,

Brian G


If you're trying to use the NSXMLDocument class on an iPhone, you're going to be sorely disappointed, because this class (and related NSXMLNode, NSXMLElement, etc classes) are not available on the phone (they ARE available in the Simulator, which can be confusing).

Take a look at libxml2 to do XML parsing on the phone. There are several free frameworks (I believe TouchXML is a good one) for doing this.

That being said, if you want to run this code on a Mac, you can use the NSXMLElement method -attributeForName: to pull out just the attribute you want.

Ben's right - while iPhone-SDK code will build with NSXMLDocument and run in the simulator, it won't work at all on the device. The docs probably mention it somewhere, but it's fairly obscure. TouchXML is part of TouchCode; you can find more information about it here.

The iPhone does have access to NSXMLParser which is a nice little sax parser. Aaron Hillegass has a good article on using NSXMLParser. It doesn't support XPath, but is pretty handy at ripping xml into your data objects.

Parsing XML in Cocoa

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top