gildarts / SWXMLHash

Simple XML parsing in Swift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SWXMLHash

SWXMLHash is a relatively simple way to parse XML in Swift. If you're familiar with NSXMLParser, this library is a simple wrapper around it. Conceptually, it provides a translation from XML to a dictionary of arrays (aka hash).

The API takes a lot of inspiration from SwiftyJSON.

Examples

All examples below can be found in the included specs.

Initialization

let xml = SWXMLHash.parse(xmlToParse)

Single Element Lookup

Given:

<root>
  <header>
    <title>Foo</title>
  </header>
  ...
</root>

Will return "Foo".

xml["root"]["header"]["title"].element?.text

Multiple Elements Lookup

Given:

<root>
  ...
  <catalog>
    <book><author>Bob</author></book>
    <book><author>John</author></book>
    <book><author>Mark</author></book>
  </catalog>
  ...
</root>

The below will return "John".

xml["root"]["catalog"]["book"][1]["author"].element?.text

Attributes Usage

Given:

<root>
  ...
  <catalog>
    <book><author id="1">Bob</author></book>
    <book><author id="123">John</author></book>
    <book><author id="456">Mark</author></book>
  </catalog>
  ...
</root>

The below will return "123".

xml["root"]["catalog"]["book"][1].element?.attributes["id"]

Returning All Elements

Given:

<root>
  ...
  <catalog>
    <book><genre>Fiction</genre></book>
    <book><genre>Non-fiction</genre></book>
    <book><genre>Technical</genre></book>
  </catalog>
  ...
</root>

The below will return "Fiction, Non-fiction, Technical".

", ".join(xml["root"]["catalog"]["book"].all.map { elem in elem["genre"].element!.text! })

Error Handling

switch xml["root"]["what"]["header"]["foo"] {
case .Element(let elem):
  // everything is good, code away!
case .Error(let error):
  // error is an NSError instance that you can deal with
}

Installation

Ultimately, this will be distributed with CocoaPods support; however, CocoaPods doesn't yet support Swift projects. In the meantime, just add SWXMLHash as a git submodule and drag SWXMLHash.swift into your project.

TODO

  • finish implementing error handling for group indexing
  • add attribute support
  • maybe add attribute look-up for elements as opposed to solely array indexing
  • add CocoaPods support once it supports Swift projects
  • more???

About

Simple XML parsing in Swift

License:MIT License