I am brand new to parsing and cannot find any tutorial that isn't outdated and doesn't raise more questions. I have a simple xml file url I am trying to parse. The xml is very simple:
<xml>
<record>
<EmpName>A Employee</EmpName>
<EmpPhone>111-222-3333</EmpPhone>
<EmpEmail>a@employee.com</EmpEmail>
<EmpAddress>12345 Fake Street</EmpAddress>
<EmpAddress1>MyTown, Mystate ZIP</EmpAddress1>
</record>
</xml>
And just wanted to save this as an NSDictionary (tags as keys and data as values). So far all I have been able to do successfully is print the xml string in the console with:
let url = NSURL(string: "http://www.urlexample.com/file.xml")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
print(task)
task.resume()
I have been through any online tutorials that I've found and are either outdated or much too complicated. Any help is appreciated.
Rob's answer for Swift 3 / 4
I wrote a pod for mapping XML to objects, called XMLMapper. (uses the same technique as the ObjectMapper)
For what you want to achieve you can simply use
XMLSerialization
class like:You can also implement the
XMLMappable
protocol like:And map the response XML into that objects by using
XMLMapper
class:UPDATE: Cover @fahim-parkar's comment.
To map an object (or many objects in an array) you use the same technique.
For example to map the following XML:
You need to create the model classes like:
Using the native
URLSession
you can map the RSS XML response usingXMLSerialization
andXMLMapper
:If you don't mind using Alamofire for the request, you will find XMLMapper/Requests subspec a lot easier using this code to map:
I hope this is helpful.
For Swift 5 , my code with my XML format :
Here is my XML Format :
With data response from API :
I'm using Alamofire for connect API
The process is simple:
XMLParser
object, passing it the data.delegate
for that parser.So, in Swift 3/4, that looks like:
The question is how do you implement the
XMLParserDelegate
methods. The three critical methods aredidStartElement
(where you prepare to receive characters),foundCharacters
(where you handle the actual values parsed), anddidEndElement
(where you save you results).You asked how to parse a single record (i.e. a single dictionary), but I'll show you a more general pattern for parsing a series of them, which is a far more common situation with XML. You can obviously see how to simplify this if you didn't need an array of values (or just grab the first one).
And
For Swift 2 rendition, see previous revision of this answer.