XML parsing in swift

2020-02-13 16:05发布

问题:

Can some body help me why the below code is not working.. I am testing it in Xcode.1 Playground

let url:NSURL! = NSURL(fileURLWithPath:"file:///Users/sss/Documents/app.xml")

var xml = NSXMLParser(contentsOfURL: url)

xml?.parse()

回答1:

Playgrounds are sandboxed, so you won't be able to just grab files from anywhere in your user folder. Here's how to add that file to your playground to make it accessible:

  1. Find your ".playground" file in the Finder
  2. Right click and choose "Show Package Contents"
  3. You should see "timeline.xctimeline", "contents.xcplayground", and "section-1.swift"
  4. Make a new folder called "Resources"
  5. Copy "app.xml" into that new folder

Now your file will be available inside the sandbox. You can retrieve it from the bundle and load it into the NSXMLParser like this:

let url: NSURL! = NSBundle.mainBundle().URLForResource("app", withExtension: "xml")
var xml = NSXMLParser(contentsOfURL: url)