For the More Curious: Parsing XML

There are two standard approaches to parsing XML. The high-level method (DOM parsing) is to use NSXMLDocument and NSXMLNode. If you have an NSData object containing the following XML:

<​?​x​m​l​ ​v​e​r​s​i​o​n​=​"​1​.​0​"​ ​e​n​c​o​d​i​n​g​=​"​U​T​F​-​8​"​?​>​
<​p​e​o​p​l​e​>​
 ​ ​<​p​e​r​s​o​n​>​
 ​ ​ ​ ​<​f​i​r​s​t​>​P​a​t​r​i​c​k​<​/​f​i​r​s​t​>​
 ​ ​ ​ ​<​l​a​s​t​>​R​o​b​i​n​s​o​n​<​/​l​a​s​t​>​
 ​ ​<​/​p​e​r​s​o​n​>​
<​/​p​e​o​p​l​e​>​

NSXMLDocument will parse it into a handy tree (Figure 28.7):

Figure 28.7  Parsed XML document

Parsed XML document

You can then traverse the tree manually or use XPath queries ...

Get Cocoa Programming for OS X: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.