Use Swift to implement a tutorial for parsing XML format data in the iOS app _swift

Source: Internet
Author: User

In iOS, a set of APIs is provided to parse XML data. In fact, it is also very simple, is nsxmlparser and nsxmlparserdelegate.

You can specify the URL to the XML directly to instantiate the Nsxmlparser

Copy Code code as follows:

Public convenience init? (Contentsofurl Url:nsurl)



Parsing the file, returning the result of a parse


Copy Code code as follows:

Nsxmlparser.parse ()-> Bool



Listening for properties of resolved nodes


Copy Code code as follows:

Nsxmlparserdelegate.parser (Parser:nsxmlparser, didstartelement elementname:string, namespaceuri:string? QualifiedName qname:string, Attributes attributedict: [string:string])



Listening for the contents of the parsing node


Copy Code code as follows:

Nsxmlparserdelegate.parser (Parser:nsxmlparser, Foundcharacters string:string)



Example:

The basic XML data parsing and printing is presented here.

1. Prepare XML data
Open Notepad and write down:

<?xml version= "1.0" encoding= "Utf-8"?>
<students>
  <student id= "001" >
      <name> Bill gates</name>
      <age>15</age>
  </student>
  <student id= "002" >
      <name>tim cook</name>
      <age>18</age>
  </student>
</students>

Save named Data.xml.

2. Parsing xml
Create a new project in Xcode, Data.xml into the new project and drag it in. Write the following code in Viewcontroller.swift:

Copy Code code as follows:



Class viewcontroller:uiviewcontroller,nsxmlparserdelegate{


Override Func Viewdidload () {


Super.viewdidload ()


Let parser = Nsxmlparser (Contentsofurl:nsurl (FileURLWithPath:NSBundle.mainBundle (). Pathforresource ("Data", OfType: "XML")!)


1


parser!. delegate = Self


parser!. Parse ()


}

    var currentnodename:string!
    func parser (Parser:nsxmlparser, didstartelement elementname:string, namespaceuri:string? QualifiedName qname:string?, attributes Attributedict: [string:string]) {
      & nbsp Currentnodename = elementname
        If elementname = "Student" {
 & nbsp;          if let id = attributedict["id"]{
             Print ("Id:\ (ID)")
            }
       }
   }

Func parser (Parser:nsxmlparser, foundcharacters string:string) {
2
Let str = String.stringbytrimmingcharactersinset (Nscharacterset.whitespaceandnewlinecharacterset ())
If str!= "" {
Print ("\ (currentnodename): \ (str)")
}
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
Dispose of any of the can is recreated.
}
}




Code comments:


1. Use of Nsxmlparser requires nsxmlparserdelegate agent


2. Remove labels for printing such as &lt;student&gt; if written directly


Copy Code code as follows:

Func parser (Parser:nsxmlparser, foundcharacters string:string) {
Print ("\ (string): \ (str)")
}



The front label will be printed out.

3. Code Run Results

id:001
name:bill Gates
age:15
id:002
name:tim Cook
age:18

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.