Parsing XML Format data for iOS development

Source: Internet
Author: User

The data in XML format is a kind of data transmission format, because it is convenient to write, the structure is clear, so it is popular with programmers, many people like to use XML format to transfer data or as a program configuration information. Now I'm going to implement parsing XML format data in iOS, using Swift in language.

Start by writing a simple XML yourself:

<data>   <person age= ">zhangsan</person>   <person age=" 2 ">lisi</person>   <person>wangwu</person>   <a>       <b>           <c>many people</c>       </b>   </a></data>
First write this XML into a file Data.xml stored in supporting files, read in the program.

(1) First implement a delegate in this viewcontroller: Nsxmlparserdelegate. The XML file is then read in Viewdidload (). The Viewdidload () method is implemented as follows:

    Override Func Viewdidload () {        super.viewdidload ()        //Do any additional setup after loading the view, typically fro M a nib.                var parser = Nsxmlparser (Contentsofurl:nsurl (FileURLWithPath:NSBundle.mainBundle (). Pathforresource ("Data", OfType: "XML")!))                parser!. delegate = self        parser!. Parse ()            }

(2) then read the head node value, such as <data>,<person>,<a>,<b>,<c> to implement a parse () method:

Func parser (Parser:nsxmlparser, didstartelement elementname:string, namespaceuri:string?, QualifiedName qname:string ?, attributes Attributedict: [Nsobject:anyobject]) {                println (elementname)    //output each of the head nodes; data,person,person,a , B,c;            }
The results are as follows: In line with our expectations.


(3) Then try to read the attribute value, such as age in XML. is also implemented in the parse () method described above. The code is as follows:

    Func parser (Parser:nsxmlparser, didstartelement elementname:string, namespaceuri:string?, QualifiedName qname:string ?, attributes Attributedict: [Nsobject:anyobject]) {                if elementname = = ' Person ' {                    if let Age:anyobject = Attribu tedict[' age ']{                            println ("Age = \ (age)")}}}    
The output results are as follows:


(4) Finally we will read the node value together with the key value contained inside. You need to rewrite a parse method in the Nsxmlparserdelegate delegate, where two overrides the Parse method are as follows:

    Func parser (Parser:nsxmlparser, didstartelement elementname:string, namespaceuri:string?, QualifiedName qname:string ?, attributes Attributedict: [Nsobject:anyobject]) {                currentnodename = elementname            }        func parser (parser: Nsxmlparser, Foundcharacters string:string?) {                var str  = string?. Stringbytrimmingcharactersinset (Nscharacterset.whitespaceandnewlinecharacterset ())            if str! = "" {                println ( "Current node= \ (currentnodename), value=\ (str!)")            }        }    
The final output is as follows: Meets the expected results.


(5) The Code of the whole program is as follows, there are more detailed comments:

Import Uikitclass Viewcontroller:uiviewcontroller, nsxmlparserdelegate{override func Viewdidload () {Super.vie Wdidload ()//Read the contents from data.xml var parser = Nsxmlparser (contentsofurl:nsurl.                Mainbundle (). Pathforresource ("Data", OfType: "xml")!)) parser!. delegate = self//delegate using XML parsing, requires override method; parser!. Parse ()} var currentnodename:string! Wait to record the name of the node currently being read; Func parser (Parser:nsxmlparser, didstartelement elementname:string, namespaceuri:string?, qua Lifiedname qname:string?, attributes Attributedict: [Nsobject:anyobject]) {println (elementname)//output                Each head node, such as a data,person,person,a,b,c; Currentnodename = elementname if elementname = = "Person" {//Read the attribute value under a node, such as the age attribute under person;                            /It may be that some person nodes do not have an age attribute and need to be judged by using if, otherwise the error will be encountered when reading a node that does not have a age:anyobject = attributedict["Age"]{ println ("Age = \ (age)"}}}} Func parser (Parser:nsxmlparser, foundcharacters string:string?) {//In the reading of the entire XML file, the spaces are also read as strings. So you need to delete blank lines and spaces;//string is the key value of this node; var str = string?. Stringbytrimmingcharactersinset (Nscharacterset.whitespaceandnewlinecharacterset ())//also need to determine whether this key value is empty, Because there are no values between the Kinsoku nodes: such as <d></d> and so on; if str! = "" {println ("current node= \ (currentnodename)            , Value=\ (str!)}} Override Func didreceivememorywarning () {super.didreceivememorywarning ()}}

In fact, the need to parse XML is most used is the client with soap to access WebService, at this time WebService many return is XML.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Parsing XML Format data for iOS development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.