11.12. Parsing XML with NSXMLParser
Problem
You want to parse an XML snippet or document.
Solution
Use the NSXMLParser
class.
Discussion
The NSXMLParser
uses a delegate
model to parse XML content. Let’s go ahead and create a simple XML file
that contains the following data (save this file as MyXML.xml in your project):
<?xml version="1.0" encoding="UTF-8"?>
<root>
<person
id=
"1"
>
<firstName>
Anthony</firstName>
<lastName>
Robbins</lastName>
<age>
51</age>
</person>
<person
id=
"2"
>
<firstName>
Richard</firstName>
<lastName>
Branson</lastName>
<age>
61</age>
</person>
</root>
Now define a property of type NSXMLParser
:
#import "AppDelegate.h"
@interface
AppDelegate
()
<
NSXMLParserDelegate
>
@property
(
nonatomic
,
strong
)
NSXMLParser
*
xmlParser
;
@end
@implementation
AppDelegate
You can also see that I have defined my app delegate as an XML
parser delegate by conforming to the NSXMLParserDelegate
protocol, which is
required for a delegate object of an XML parser of type NSXMLParser
. Now let’s read the MyXML.xml file from the disk and pass it to
your XML parser:
-
(
BOOL
)
application:
(
UIApplication
*
)
application
didFinishLaunchingWithOptions:
(
NSDictionary
*
)
launchOptions
{
NSString
*
xmlFilePath
=
[[
NSBundle
mainBundle
]
pathForResource
:
@"MyXML"
ofType:
@"xml"
];
NSData
*
xml
=
[[
NSData
alloc
]
initWithContentsOfFile
:
xmlFilePath
];
self
.
xmlParser
=
[[
NSXMLParser
alloc
]
initWithData
:
xml
];
self
.
xmlParser
.
delegate
=
self
;
if
([
self
.
xmlParser
parse
]){
NSLog
(
@"The XML is parsed."
);
}
else
{
NSLog
(
@"Failed to parse the ...
Get iOS 7 Programming Cookbook 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.