Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/swiftpm.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: SwiftPM

on:
push:
branches: [master]
pull_request:
release:
types: [published]

permissions:
contents: read

jobs:
tests:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-15]
runs-on: ${{ matrix.os }}
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Inspect package
run: |
swift --version
swift package dump-package
swift package describe
- name: Test package in Debug
run: swift test --jobs 2
- name: Test package in Release
run: swift test -c release --jobs 2
- name: Test independent consumer
env:
PACKAGE_VERSION: ${{ github.event.release.tag_name }}
EXPECTED_REVISION: ${{ github.sha }}
run: bash scripts/test-consumer.sh
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,6 @@ fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output

# SwiftPM IDE state
.swiftpm/
31 changes: 15 additions & 16 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,28 +1,27 @@
// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

// swift-tools-version:5.3
import PackageDescription

let package = Package(
name: "SwiftXMLParser",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "SwiftXMLParser",
targets: ["SwiftXMLParser"]),
platforms: [
.iOS("8.0"),
.macOS("10.9"),
.tvOS("9.0"),
.watchOS("2.0")
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
products: [
.library(name: "SwiftXMLParser", targets: ["SwiftXMLParser"])
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftXMLParser",
dependencies: []),
path: "Sources"
),
.testTarget(
name: "SwiftXMLParserTests",
dependencies: ["SwiftXMLParser"]),
]
dependencies: ["SwiftXMLParser"],
path: "Tests/SwiftXMLParserTests"
)
],
swiftLanguageVersions: [.v5]
)
88 changes: 88 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,89 @@
# SwiftXMLParser

A Foundation-based XML-to-dictionary and dictionary-to-XML utility written in
Swift. Supports Swift Package Manager and retains its CocoaPods and Xcode
project layouts.

## Installation

### Swift Package Manager

Requires Swift 5.3 or later. In Xcode, choose **File > Add Package Dependencies**,
enter `https://github.com/100mango/SwiftXMLParser.git`, and add the
`SwiftXMLParser` product to your target. Select version `0.2.0` or later.

For a `Package.swift` dependency:

```swift
.package(url: "https://github.com/100mango/SwiftXMLParser.git", from: "0.2.0")
```

Then add `.product(name: "SwiftXMLParser", package: "SwiftXMLParser")` to your
target's `dependencies` and use `import SwiftXMLParser`.

The package has no third-party dependencies or bundled resources. Its Apple
platform declarations preserve the existing podspec's deployment minimums:
iOS 8.0, macOS 10.9, tvOS 9.0, and watchOS 2.0. The selected Swift/Xcode SDK may
impose newer minimums. Linux uses FoundationXML for XML parsing.

### CocoaPods

The existing `SwiftXMLParser.podspec` and `Sources/` layout are retained. To use
the repository directly from a Podfile:

```ruby
pod 'SwiftXMLParser', :git => 'https://github.com/100mango/SwiftXMLParser.git', :tag => '0.2.0'
```

## Usage

```swift
import SwiftXMLParser

let result = SwiftXMLParser.makeDic(
string: "<root><item>one</item><item>two</item></root>"
)
// ["root": ["item": ["one", "two"]]]

let xml = SwiftXMLParser.makeXML(dic: ["root": ["item": "value"]])
// <root><item><![CDATA[value]]></item></root>
```

Repeated elements become arrays. By default, attributes are stored under
`_XMLAttributes`; set an instance's `attributesAsStandaloneDic` to `false` to
place attributes alongside its child keys. Text on an element that also has
attributes or children uses the instance's `TextKey`. Invalid XML returns `nil`. CDATA contents are read as text, including their
whitespace.

## Model limitations

This is a dictionary convenience model for element-only XML, not a lossless
implementation of the full XML document model. Mixed content such as
`<root>before<child>inside</child>after</root>` is unsupported: the legacy parser
can combine the leading text with the child value, and dictionary keys cannot
preserve the original ordering of text and child elements. Avoid mixed content
when parsing or round-tripping documents. Empty elements without attributes are
omitted. The serializer expects valid XML element/attribute names and does not
escape a `]]>` sequence inside a value.

## Testing

Run the full package suite on macOS or Linux:

```sh
swift package describe
swift test
swift test -c release
bash scripts/test-consumer.sh
```

The `SwiftPM` workflow runs Debug and Release tests and an independent
consuming package on standard Linux and macOS runners. On a GitHub release,
the consumer resolves the exact published tag and verifies its commit revision. It does not sign code or upload build artifacts. Tests cover
repeated and nested elements, attribute modes, malformed input, parser reuse,
serialization, CDATA, Unicode/BOM input, invalid document variants, and
element-only round trips, alongside the original tests.

## License

MIT. See [LICENSE](LICENSE).
125 changes: 56 additions & 69 deletions Sources/SwiftXMLParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
//

import Foundation
#if canImport(FoundationXML)
import FoundationXML
#endif

public class SwiftXMLParser: NSObject {

Expand All @@ -20,9 +23,10 @@ public class SwiftXMLParser: NSObject {
public var attributesAsStandaloneDic = true


var dicStack = [NSMutableDictionary]()
var dicStack = [[String: Any]]()
var textInProcess = ""
var xml = ""
private var sawRootElement = false

}

Expand Down Expand Up @@ -54,14 +58,19 @@ public extension SwiftXMLParser {
func makeDic(data: Data) -> [String:Any]? {

//reset
dicStack = [NSMutableDictionary]()
dicStack = [[String: Any]]()
textInProcess = ""
dicStack.append(NSMutableDictionary())
sawRootElement = false
dicStack.append([:])

guard !data.isEmpty else { return nil }

let parser = XMLParser(data: data)
parser.delegate = self
if parser.parse() == true {
return dicStack.first as? [String : Any]
// Some FoundationXML versions report parse errors through parserError
// even when parse() returns true after recovering the document.
if parser.parse(), parser.parserError == nil, sawRootElement, dicStack.count == 1 {
return dicStack.first
} else {
return nil
}
Expand Down Expand Up @@ -131,48 +140,21 @@ extension SwiftXMLParser: XMLParserDelegate {

public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {

//get parent
guard let parentDic = dicStack.last else {
fatalError("should not be nil")
}

// generate current
let childDic = NSMutableDictionary()
sawRootElement = true
var childDic = [String: Any]()
if attributesAsStandaloneDic {
//transformed attributes as a standalone dictionary
//it will help us transform it back to xml
if attributeDict.count > 0 {
childDic.setObject(attributeDict, forKey: AttributesKey as NSString)
if !attributeDict.isEmpty {
childDic[AttributesKey] = attributeDict
}
} else {
//attributes as key,value pair
childDic.addEntries(from: attributeDict)
}

// if element name appears more than once, they need to be grouped as array
if let existingValue = parentDic[elementName] {

let array: NSMutableArray

if let currentArray = existingValue as? NSMutableArray {
array = currentArray
} else {
//If there is no array, create a new array, add the original value
array = NSMutableArray()
array.add(existingValue)
//Replace the original value with an array
parentDic[elementName] = array
for (key, value) in attributeDict {
childDic[key] = value
}
//Add a new element to the array
array.add(childDic)

} else {
//unique element, inserted into parent
parentDic[elementName] = childDic
dicStack[dicStack.endIndex-1] = parentDic
}

//add to stack, track it

// Keep unfinished elements on the stack. Inserting them only when complete
// avoids relying on NSMutableDictionary/NSMutableArray reference bridging,
// which differs between Darwin Foundation and swift-corelibs-foundation.
dicStack.append(childDic)
}

Expand All @@ -181,42 +163,47 @@ extension SwiftXMLParser: XMLParserDelegate {
textInProcess.append(append)
}

public func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) {
// XMLParser reports CDATA separately from foundCharacters. Preserve its
// contents, including whitespace and characters that need XML escaping.
if let text = String(data: CDATABlock, encoding: .utf8) {
textInProcess.append(text)
}
}

public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {

//Get the dic representing the current element
guard let value = dicStack.last else {
guard var value = dicStack.popLast(), !dicStack.isEmpty else {
fatalError("should not be nil")
}
let parent = dicStack[dicStack.endIndex - 2]

if textInProcess.count > 0 {
if value.count > 0 {
value[TextKey] = textInProcess
defer { textInProcess = "" }

let completedValue: Any
if !textInProcess.isEmpty {
if value.isEmpty {
completedValue = textInProcess
} else {
//If the current element has only value, no Attributes, like <list> 1 </ list>
//Replace the dictionary directly with string
if let array = parent[elementName] as? NSMutableArray {
//parent now looks like: {"list" : [1,{}]}
//Replace the empty dictionary with a string
array.removeLastObject()
array.add(textInProcess)
} else {
//parent now looks like: {"list" : {} }
//Replace the empty dictionary with a string
parent[elementName] = textInProcess
}
value[TextKey] = textInProcess
completedValue = value
}
} else if !value.isEmpty {
completedValue = value
} else {
//If value is empty and the element has no Attributes, delete the node
if value.count == 0 {
parent.removeObject(forKey: elementName)
// Empty elements without attributes are omitted, as before.
return
}

let parentIndex = dicStack.count - 1
if let existingValue = dicStack[parentIndex][elementName] {
if var array = existingValue as? [Any] {
array.append(completedValue)
dicStack[parentIndex][elementName] = array
} else {
dicStack[parentIndex][elementName] = [existingValue, completedValue]
}
} else {
dicStack[parentIndex][elementName] = completedValue
}

//reset
textInProcess = ""
//Finished processing the current element, pop
dicStack.removeLast()
}

public func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
Expand Down
10 changes: 5 additions & 5 deletions SwiftXMLParser.podspec
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
Pod::Spec.new do |s|
s.name = "SwiftXMLParser"
s.version = "0.1"
s.summary = ""
s.version = "0.2.0"
s.summary = "A Foundation-based XML dictionary utility written in Swift."
s.description = <<-DESC
Your description here.
Parse element-only XML into dictionaries and serialize dictionary values as XML.
DESC
s.homepage = ""
s.homepage = "https://github.com/100mango/SwiftXMLParser"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "100mango" => "100mango@gmail.com" }
s.social_media_url = ""
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.9"
s.watchos.deployment_target = "2.0"
s.tvos.deployment_target = "9.0"
s.source = { :git => ".git", :tag => s.version.to_s }
s.source = { :git => "https://github.com/100mango/SwiftXMLParser.git", :tag => s.version.to_s }
s.source_files = "Sources/**/*"
s.frameworks = "Foundation"
end
Loading
Loading