• Stars
    star
    575
  • Rank 77,594 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 8 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple XML Parser implemented in Swift

swiftyxmlparserlogo

Swift 5.0 Carthage compatible Version License Platform

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 9.0+
  • tvOS 9.0+
  • macOS 10.10+
  • Swift 5.0

Installation

Carthage

1. create Cartfile

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

2. install

> carthage update

CocoaPods

1. create Podfile

platform :ios, '9.0'
use_frameworks!

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

2. install

> pod install

Example

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", 0].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
let str = """
<ResultSet>
    <Result>
        <Hit index=\"1\">
            <Name>Item1</Name>
        </Hit>
        <Hit index=\"2\">
            <Name>Item2</Name>
        </Hit>
    </Result>
</ResultSet>
"""

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

let string = String(decoding: data, as: UTF8.self)

xml = XML.parse(data) // -> XML.Accessor
  • with invalid character
let srt = "<xmlopening>@ß123\u{1c}</xmlopening>"

let xml = XML.parse(str.data(using: .utf8))

if case .failure(XMLError.interruptedParseError) = xml {
  print("invalid character")
}

For more, see https://developer.apple.com/documentation/foundation/xmlparser/errorcode

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>
  • with @dynamicMemberLookup
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

7. Access CDATA

let str = """
<Data name="DATE">
    <value><![CDATA[2018-07-08]]></value>
</Data>
"""

// parse xml document
let xml = try! XML.parse(str)
        
if let cdata = xml.Data.value.element?.CDATA, 
   let cdataStr = String(data: cdata, encoding: .utf8) {
   print(cdataStr) // -> "2018-07-08"
}

7. Count child Elements

let numberOfHits = xml.ResultSet.Result.Hit.all?.count 

8. Check error

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

9. Access as SequenceType

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

10. Generate XML document

print(Converter(xml.ResultSet).makeDocument())

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 SwiftyXMLParser.

Migration Guide

Current master branch is supporting Xcode10. If you wanna use this library with legacy swift version, read release notes and install the last compatible version.

License

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

More Repositories

1

NGT

Nearest Neighbor Search with Neighborhood Graph and Tree for High-dimensional Data
C++
1,221
star
2

objc2swift

Open Source Obj-C to Swift Converter.
Scala
1,033
star
3

JGLUE

JGLUE: Japanese General Language Understanding Evaluation
Python
294
star
4

UICollectionViewSplitLayout

UICollectionViewSplitLayout makes collection view more responsive.
Swift
241
star
5

AnnexML

AnnexML is a multi-label classifier designed for extremely large label space.
C++
106
star
6

yskip

Incremental Skip-gram Model with Negative Sampling
Shell
68
star
7

yosegi

Yosegi is a Schema-less columnar storage format. Provide flexible representation like JSON and efficient reading similar to other columnar storage formats.
Java
63
star
8

XCMetricsAggregator

Automation tool for Xcode Metrics Organizer with AppleScript
Ruby
62
star
9

YJCaptions

60
star
10

bakusoku-jsonp

Codeless Blog Widgets framework
JavaScript
60
star
11

AppFeedback-ios

📸 You can post feedback messages and screenshots to Slack from your iOS app! 🎥
Objective-C
42
star
12

ngtd

Serving NGT over HTTP or gRPC ※This project is not maintained. We have moved to a new product, [Vald](https://vald.vdaas.org) .
Go
38
star
13

k2hash

K2HASH - NoSQL Key Value Store(KVS) library
C++
36
star
14

authorization-proxy

Moved to https://github.com/AthenZ/authorization-proxy
Go
35
star
15

presto_exporter

Go
34
star
16

k2hftfuse

File transaction by FUSE-based file system
C++
32
star
17

gongt

NGT Go client library
Go
29
star
18

fullock

Fast User Level LOCK library
C++
26
star
19

yjlogin-ios-sdk

Yahoo! JAPAN Login iOS SDK
Swift
26
star
20

ja-vg-vqa

26
star
21

gpu-monitoring-exporter

Prometheus exporter for GPU process metrics.
Shell
26
star
22

jenkins-with-docker-demo

Shell
25
star
23

lcom4go

Compute LCOM4, Lack of Cohesion of Methods metrics ver.4, for golang projects.
Go
21
star
24

yconnect-php-sdk

YConnect PHP SDK
PHP
21
star
25

vespa-tutorial

Japanese tutorial for Vespa
Shell
20
star
26

AppFeedback-android

📸 You can post feedback messages and screenshots to Slack from your Android app! 🎥
Java
20
star
27

presto-audit

THIS REPOSITORY IS DEPRECATED
Java
19
star
28

garm

Garm is k8s authorization webhook (SubjectAccessReview API) server for Athenz. Moved to https://github.com/AthenZ/garm
Go
17
star
29

chmpx

Consistent Hashing Mq inProcess data eXchange
C++
17
star
30

docker-continuous-integration-workflow

2014/02/12 Docker Meetup in Tokyo #1 での発表内容です。
Ruby
17
star
31

geobleu

Python implementation of GEO-BLEU, a similarity evaluation method for trajectories
Python
17
star
32

MultitaskingSample

iOS 7の新機能、BackgroundFetch, SilentPushNotification, BackgroundTransferを利用したサンプルコードです。
Objective-C
16
star
33

athenz-authorizer

athenz policy management library for golang. Moved to https://github.com/AthenZ/athenz-authorizer
Go
15
star
34

athenz-client-sidecar

Moved to https://github.com/AthenZ/athenz-client-sidecar
Go
15
star
35

vespa-kuromoji-linguistics

Java
15
star
36

k2hdkc

k2hdkc is k2hash based distributed kvs cluster
C++
13
star
37

big3store

Erlang
12
star
38

VFD-Dataset

Python
11
star
39

k2htp_dtor

K2HASH Distributed Transaction Of Repeater
C++
10
star
40

textwebapi-cookbook

Cookbook for the Text Analysis Web API provided by Yahoo! DEVELOPER NETWORK.
Jupyter Notebook
10
star
41

solr-plugin-samples

Java
9
star
42

VSU-Dataset

8
star
43

yconnect-servlet-sdk

YConnect Servlet SDK
Java
8
star
44

DynamicsSample

iOS 7の新機能、UIKit Dynamics、Motion Effectsを利用したサンプルコードです。
Objective-C
6
star
45

ConfigCacheBundle

Symfony ConfigCacheBundle for easier handling of user-defined configuration file cache
PHP
6
star
46

AntPickax

AntPickax provides basic libraries, components and systems
6
star
47

yjlogin-android-sdk

Kotlin
5
star
48

chmpx_nodejs

CHMPX nodejs addon library - Consistent Hashing Mq inProcess data eXchange
C++
5
star
49

k2hr3

K2HR3 - K2Hdkc based Resource and Roles and policy Rules
5
star
50

yosegi-spark

Java
5
star
51

hubot-shuffle

hubot-shuffle add shuffle system.
CoffeeScript
5
star
52

yosegi-hive

This is Yosegi's Hive plugin. This can write and read tables with Hive.
Java
5
star
53

k2hr3_osnl

K2HR3 OpenStack Notification Listener - K2Hdkc based Resource and Roles and policy Rules
Python
4
star
54

embulk-output-solr

Java
4
star
55

fastlane-plugin-setup_app_feedback_sdk

Fastlane plugin that update Info.plist for AppFeedback SDK
Ruby
4
star
56

k2hash_phpext

PHP Extension library for K2HASH
C
4
star
57

k2hr3_utils

K2HR3 Utils - Utils for K2Hdkc based Resource and Roles and policy Rules
Shell
4
star
58

k2hr3_app

K2HR3 Web Application - K2Hdkc based Resource and Roles and policy Rules
JavaScript
4
star
59

k2hr3_api

K2HR3 REST API - K2Hdkc based Resource and Roles and policy Rules
JavaScript
4
star
60

k2htp_mdtor

K2Hash Transaction Plugin for Multiple Distributed Transaction Of Repeater
Shell
4
star
61

k2hr3_helm_chart

Helm Chart for K2HR3
Shell
3
star
62

k2hdkc_java

K2HDKC Java library - k2hash based distributed kvs cluster
Java
3
star
63

k2hdkc_go

K2HDKC Go library - k2hash based distributed kvs cluster
Go
3
star
64

yosegi-tools

Java
3
star
65

k2hash_go

K2HASH Go library - NoSQL Key Value Store(KVS) library
Go
3
star
66

yj-ci-dataset

3
star
67

k2hr3_cli

K2HR3 Command Line Interface
Shell
3
star
68

embulk-parser-xml2

Java
3
star
69

k2hr3_sidecar

K2HR3 Container Registration Sidecar - K2Hdkc based Resource and Roles and policy Rules
Shell
3
star
70

k2hdkc_python

K2HDKC Python library - k2hash based distributed kvs cluster
Python
3
star
71

k2hdkc_dbaas

Database as a Service for K2HDKC
Python
3
star
72

k2hash_python

K2HASH Python library - NoSQL Key Value Store(KVS) library
Python
3
star
73

yosegi-hadoop

Java
3
star
74

k2hdkc_nodejs

K2HDKC nodejs addon library - k2hash based distributed kvs cluster
JavaScript
3
star
75

k2hash_nodejs

K2HASH nodejs addon library - NoSQL Key Value Store(KVS) nodejs library
JavaScript
3
star
76

k2hash_java

K2HASH Java library - NoSQL Key Value Store(KVS) library
Java
3
star
77

yosegi-avro

Java
2
star
78

k2hdkc_dbaas_override_conf

K2HDKC DBaaS Override Configuration
Shell
2
star
79

k2hdkc_dbaas_k8s_cli

K2HDKC DBaaS on kubernetes Command Line Interface - K2HR3 CLI Plugin
Shell
2
star
80

k2hr3_get_resource

K2HR3 Utilities - Get K2HR3 Resource Helper for Systemd service
Shell
2
star
81

k2hdkc_dbaas_cli

K2HDKC DBaaS Command Line Interface - K2HR3 CLI Plugin
Shell
2
star
82

hubot-package-version-release

publish release on GitHub based package.json
CoffeeScript
2
star
83

k2hdkc_helm_chart

Helm Chart for K2HDKC DBaaS
Shell
2
star
84

k2hr3client_python

k2hr3client_python is an official Python WebAPI client for k2hr3.
Python
2
star
85

k2hdkc_phpext

PHP Extension library for K2HDKC
PHP
1
star
86

yosegi-example

Java
1
star
87

chmpx_phpext

PHP Extension library for CHMPX
PHP
1
star
88

yosegi-legacy

Java
1
star