Code Monkey home page Code Monkey logo

swiftyxmlparser's Introduction

SwiftyXMLParser

Carthage compatible Cocoapods compatible

Simple XML Parser implemented in Swift

What's this?

This is a XML parser inspired by SwiftyJSON and SWXMLHash.

NSXMLParser in Foundation framework is a kind of "SAX" parser. It has enough performance but is a little inconvenient. So we have implemented "DOM" parser wrapping it.

Feature

  • access XML Document with "subscript".
  • access XML Document as Sequence.
  • easy debugging XML pathes.

Requirement

  • iOS 7.0+
  • Swift 2.0+

Installation

Carthage

1. create Cartfile

github "https://github.com/yahoojapan/SwiftyXMLParser"

2. install

> carthage update

CocoaPods

1. create Podfile

platform :ios, '8.0'
use_frameworks!

pod "SwiftyXMLParser", :git => 'https://github.com/yahoojapan/SwiftyXMLParser.git'

2. install

> pod install

Example

    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)
    }

Usage

1. Parse XML

  • from String
let string = "<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
let string = "<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

let element = xml["ResultSet"] // -> XML.Accessor

3. Access grandchild Elements

  • with String
let element = xml["ResultSet"]["Result"] // -> <Result><Hit index=\"1\"><Name>Item1</Name></Hit><Hit index=\"2\"><Name>Item2</Name></Hit></Result>
  • with Array
let path = ["ResultSet", "Result"]
let element = xml[path] // -> <Result><Hit index=\"1\"><Name>Item1</Name></Hit><Hit index=\"2\"><Name>Item2</Name></Hit></Result>
  • with Variadic
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

let element = xml["ResultSet", "Result", "Hit", 1] // -> <Hit index=\"2\"><Name>Item2</Name></Hit>

5. Access attribute in Element

if let attributeValue = xml["ResultSet", "Result", "Hit", 1].attributes?["index"] {
  print(attributeValue) // -> 2
}

6. Access text in Element

  • with optional binding
if let text = xml["ResultSet", "Result", "Hit", 1, "Name"].text {
    print(text) // -> Item2
} 
  • with custom operation
struct Entity {
  var name = ""
}
let entity = Entity()
entity.name ?= xml["ResultSet", "Result", "Hit", 1, "Name"].text // assign if it has text
  • convert Int and assign
struct Entity {
  var name: Int = 0
}
let entity = Entity()
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
struct Entity {
  var names = [String]()
}
let entity = Entity()
entity.names ?<< xml["ResultSet", "Result", "Hit", 1, "Name"].text // assign if it has text

Check error

print(xml["ResultSet", "Result", "TypoKey"]) // -> "TypoKey not found."

Access as SequenceType

  • for-in
for element in xml["ResultSet", "Result", "Hit"] {
  print(element.text)
}
  • map
xml["ResultSet", "Result", "Hit"].map { $0["Name"].text }

Work with Alamofire

SwiftyXMLParser goes well with Alamofire. You can parse the response easily.

import Alamofire
import SwiftyXMLParser

Alamofire.request(.GET, "https://itunes.apple.com/us/rss/topgrossingapplications/limit=10/xml")
         .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.
            }
        }

In addition, there is the extension of Alamofire to combine with SwiftyXMLPraser.

License

This software is released under the MIT License, see LICENSE.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.