Import Uikitclass Viewcontroller:uiviewcontroller, nsxmlparserdelegate{override func Viewdidload () {Super.vie Wdidload ()///Create Xmlparser object, incoming data file in XML format//var parser=nsxmlparser (Contentsofurl:nsurl (Fileurlwithpath:nsbun Dle.mainbundle (). Pathforresource ("Data", OfType: "xml")!)! Parsing XML data in string format let string= "<data><person age= ' >zhangsan</person><person age= ' >lisi& ' Lt;/person><person>wangwu</person><a><b><c>data</c></b></a> </data> "//String conversion to NSData format two ways can be converted//let string1:nsstring = string//let Data1:nsdata = Strin G1.datausingencoding (nsutf8stringencoding)! var data1:nsdata = NSData (bytes:string, Length:count (String)) var parser = Nsxmlparser (data:data1)//Delegate Parser.delegate = self//start parsing parser.parse ()} var elementname:string = "" var Attributedice: [Nsobject:anyobject] = [NSOBJECT:ANYOBJect] ()/* will execute this method when parsing begins, this method can get the node name and properties */func parser (Parser:nsxmlparser, didstartelement elementname : String, namespaceuri:string?, QualifiedName qname:string?, attributes Attributedict: [Nsobject:anyobject]) {s elf.elementname=elementname//the node name of the current loop node self.attributedice=attributedict//All properties of the current loop node println (elementname) }/* Get the contents of the node by this method */Func parser (Parser:nsxmlparser, foundcharacters string:string?) {////Because the XML may contain newline-compliant spaces, this method can be used to remove line-wrapping in accordance with the space var str:string! = String?. Stringbytrimmingcharactersinset (Nscharacterset.whitespaceandnewlinecharacterset ()) if str! = "" {println ("\ (elementname): \ (str)")} } override func Didreceivememorywarning () {super.didreceivememorywarning ()//Dispose of any resources t Hat can be recreated. }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
XML data parsing under ISO Swift