Skip to content

Commit

Permalink
Merge pull request #21 from yahoojapan/swift4.2
Browse files Browse the repository at this point in the history
Swift4.2 Support
  • Loading branch information
kazuhiro4949 authored Sep 19, 2018
2 parents 1ddcad0 + fcc6a96 commit cfe0448
Show file tree
Hide file tree
Showing 16 changed files with 522 additions and 42 deletions.
125 changes: 85 additions & 40 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,54 +56,95 @@ pod "SwiftyXMLParser", :git => 'https://github.com/yahoojapan/SwiftyXMLParser.gi
# Example

```swift
let string = "<ResultSet><Result><Hit index=\"1\"><Name>Item1</Name></Hit><Hit index=\"2\"><Name>Item2</Name></Hit></Result></ResultSet>"

// parse xml document
xml = try! XML.parse(string)

// access xml element
let accessor = xml["ResultSet"]

// access XML Text
let text = xml["ResultSet", "Result", "Hit", 0, "Name"].text {
print("exsists path & text in XML Element")
}

// access XML Attribute
let index = xml["ResultSet", "Result", "Hit"].attributes?["index"] {
print("exsists path & an attribute in XML Element")
}

// enumerate child Elements in the parent Element
for hit in xml["ResultSet", "Result", "Hit"] {
print("enumarate existing XML Elements")
}

// check if the XML path is wrong
if case .Failure(let error) = xml["ResultSet", "Result", "TypoKey"] {
print(error)
}
import SwiftyXMLParser

let str = """
<ResultSet>
<Result>
<Hit index=\"1\">
<Name>Item1</Name>
</Hit>
<Hit index=\"2\">
<Name>Item2</Name>
</Hit>
</Result>
</ResultSet>
"""

// parse xml document
let xml = try! XML.parse(str)

// access xml element
let accessor = xml["ResultSet"]

// access XML Text

if let text = xml["ResultSet", "Result", "Hit", 0, "Name"].text {
print(text)
}

if let text = xml.ResultSet.Result.Hit[0].Name.text {
print(text)
}

// access XML Attribute
if let index = xml["ResultSet", "Result", "Hit"].attributes["index"] {
print(index)
}

// enumerate child Elements in the parent Element
for hit in xml["ResultSet", "Result", "Hit"] {
print(hit)
}

// check if the XML path is wrong
if case .failure(let error) = xml["ResultSet", "Result", "TypoKey"] {
print(error)
}
```

# Usage
### 1. Parse XML
+ from String
```swift
let string = "<ResultSet><Result><Hit index=\"1\"><Name>Item1</Name></Hit><Hit index=\"2\"><Name>Item2</Name></Hit></Result></ResultSet>"
let str = """
<ResultSet>
<Result>
<Hit index=\"1\">
<Name>Item1</Name>
</Hit>
<Hit index=\"2\">
<Name>Item2</Name>
</Hit>
</Result>
</ResultSet>
"""

xml = try! XML.parse(string) // -> XML.Accessor
```
+ from NSData
```swift
let string = "<ResultSet><Result><Hit index=\"1\"><Name>Item1</Name></Hit><Hit index=\"2\"><Name>Item2</Name></Hit></Result></ResultSet>"
let str = """
<ResultSet>
<Result>
<Hit index=\"1\">
<Name>Item1</Name>
</Hit>
<Hit index=\"2\">
<Name>Item2</Name>
</Hit>
</Result>
</ResultSet>
"""

let data = string.dataUsingEncoding(NSUTF8StringEncoding)

xml = XML.parse(data) // -> XML.Accessor
```

### 2. Access child Elements
```swift
let element = xml["ResultSet"] // -> XML.Accessor
let element = xml.ResultSet // -> XML.Accessor
```

### 3. Access grandchild Elements
Expand All @@ -120,20 +161,24 @@ let element = xml[path] // -> <Result><Hit index=\"1\"><Name>Item1</Name></Hit><
```swift
let element = xml["ResultSet", "Result"] // -> <Result><Hit index=\"1\"><Name>Item1</Name></Hit><Hit index=\"2\"><Name>Item2</Name></Hit></Result>
```
+ with @dynamicMemberLookup
```swift
let element = xml.ResultSet.Result // -> <Result><Hit index=\"1\"><Name>Item1</Name></Hit><Hit index=\"2\"><Name>Item2</Name></Hit></Result>
```
### 4. Access specific grandchild Element
```swift
let element = xml["ResultSet", "Result", "Hit", 1] // -> <Hit index=\"2\"><Name>Item2</Name></Hit>
let element = xml.ResultSet.Result.Hit[1] // -> <Hit index=\"2\"><Name>Item2</Name></Hit>
```
### 5. Access attribute in Element
```swift
if let attributeValue = xml["ResultSet", "Result", "Hit", 1].attributes?["index"] {
if let attributeValue = xml.ResultSet.Result.Hit[1].attributes?["index"] {
print(attributeValue) // -> 2
}
```
### 6. Access text in Element
+ with optional binding
```swift
if let text = xml["ResultSet", "Result", "Hit", 1, "Name"].text {
if let text = xml.ResultSet.Result.Hit[1].Name.text {
print(text) // -> Item2
}
```
Expand All @@ -143,15 +188,15 @@ struct Entity {
var name = ""
}
let entity = Entity()
entity.name ?= xml["ResultSet", "Result", "Hit", 1, "Name"].text // assign if it has text
entity.name ?= xml.ResultSet.Result.Hit[1].Name.text // assign if it has text
```
+ convert Int and assign
```swift
struct Entity {
var name: Int = 0
}
let entity = Entity()
entity.name ?= xml["ResultSet", "Result", "Hit", 1, "Name"].int // assign if it has Int
entity.name ?= xml.ResultSet.Result.Hit[1].Name.int // assign if it has Int
```
and there are other syntax sugers, bool, url and double.
+ assign text into Array
Expand All @@ -160,23 +205,23 @@ struct Entity {
var names = [String]()
}
let entity = Entity()
entity.names ?<< xml["ResultSet", "Result", "Hit", 1, "Name"].text // assign if it has text
entity.names ?<< xml.ResultSet.Result.Hit[1].Name.text // assign if it has text
```
### Check error
```swift
print(xml["ResultSet", "Result", "TypoKey"]) // -> "TypoKey not found."
print(xml.ResultSet.Result.TypoKey) // -> "TypoKey not found."
```

### Access as SequenceType
+ for-in
```swift
for element in xml["ResultSet", "Result", "Hit"] {
for element in xml.ResultSet.Result.Hit {
print(element.text)
}
```
+ map
```swift
xml["ResultSet", "Result", "Hit"].map { $0["Name"].text }
xml.ResultSet.Result.Hit.map { $0.Name.text }
```

## Work with Alamofire
Expand All @@ -190,7 +235,7 @@ Alamofire.request(.GET, "https://itunes.apple.com/us/rss/topgrossingapplications
.responseData { response in
if let data = response.data {
let xml = XML.parse(data)
print(xml["feed", "entry", 0, "title"].text) // outputs the top title of iTunes app raning.
print(xml.feed.entry[0].title.text) // outputs the top title of iTunes app raning.
}
}
```
Expand Down
4 changes: 2 additions & 2 deletions SwiftyXMLParser.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 4.0;
SWIFT_VERSION = 4.2;
};
name = Debug;
};
Expand All @@ -416,7 +416,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 4.0;
SWIFT_VERSION = 4.2;
};
name = Release;
};
Expand Down
6 changes: 6 additions & 0 deletions SwiftyXMLParser/Accessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ extension XML {


*/
@dynamicMemberLookup
public enum Accessor: CustomStringConvertible, Swift.Sequence {
case singleElement(Element)
case sequence([Element])
Expand All @@ -56,6 +57,11 @@ extension XML {
self = .failure(error)
}


public subscript(dynamicMember member: String) -> XML.Accessor {
return self[member]
}

/**
If Accessor object has a correct XML path, return XML element, otherwith return error

Expand Down
45 changes: 45 additions & 0 deletions iOS Sample/SwiftyXMLParser.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import SwiftyXMLParser

let str = """
<ResultSet>
<Result>
<Hit index=\"1\">
<Name>Item1</Name>
</Hit>
<Hit index=\"2\">
<Name>Item2</Name>
</Hit>
</Result>
</ResultSet>
"""

// parse xml document
let xml = try! XML.parse(str)

// access xml element
let accessor = xml["ResultSet"]

// access XML Text

if let text = xml["ResultSet", "Result", "Hit", 0, "Name"].text {
print(text)
}

if let text = xml.ResultSet.Result.Hit[0].Name.text {
print(text)
}

// access XML Attribute
if let index = xml["ResultSet", "Result", "Hit"].attributes["index"] {
print(index)
}

// enumerate child Elements in the parent Element
for hit in xml["ResultSet", "Result", "Hit"] {
print(hit)
}

// check if the XML path is wrong
if case .failure(let error) = xml["ResultSet", "Result", "TypoKey"] {
print(error)
}
4 changes: 4 additions & 0 deletions iOS Sample/SwiftyXMLParser.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>
<timeline fileName='timeline.xctimeline'/>
</playground>
46 changes: 46 additions & 0 deletions iOS Sample/iOS Sample/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// AppDelegate.swift
// iOS Sample
//
// Created by Kazuhiro Hayashi on 2018/07/02.
// Copyright © 2018年 Kazuhiro Hayashi. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

Loading

0 comments on commit cfe0448

Please sign in to comment.