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 <student> 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