diff --git a/.github/workflows/swiftpm.yml b/.github/workflows/swiftpm.yml new file mode 100644 index 0000000..fb3ba8b --- /dev/null +++ b/.github/workflows/swiftpm.yml @@ -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 diff --git a/.gitignore b/.gitignore index d534044..740d8fd 100644 --- a/.gitignore +++ b/.gitignore @@ -65,3 +65,6 @@ fastlane/report.xml fastlane/Preview.html fastlane/screenshots fastlane/test_output + +# SwiftPM IDE state +.swiftpm/ diff --git a/Package.swift b/Package.swift index 5b62610..a58b1e7 100644 --- a/Package.swift +++ b/Package.swift @@ -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] ) diff --git a/README.md b/README.md index f1032eb..fee56f3 100644 --- a/README.md +++ b/README.md @@ -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: "onetwo" +) +// ["root": ["item": ["one", "two"]]] + +let xml = SwiftXMLParser.makeXML(dic: ["root": ["item": "value"]]) +// +``` + +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 +`beforeinsideafter` 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). diff --git a/Sources/SwiftXMLParser.swift b/Sources/SwiftXMLParser.swift index b2318d8..1b02301 100644 --- a/Sources/SwiftXMLParser.swift +++ b/Sources/SwiftXMLParser.swift @@ -7,6 +7,9 @@ // import Foundation +#if canImport(FoundationXML) +import FoundationXML +#endif public class SwiftXMLParser: NSObject { @@ -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 } @@ -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 } @@ -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) } @@ -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 1 - //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) { diff --git a/SwiftXMLParser.podspec b/SwiftXMLParser.podspec index 6ea246e..e044c57 100644 --- a/SwiftXMLParser.podspec +++ b/SwiftXMLParser.podspec @@ -1,11 +1,11 @@ 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 = "" @@ -13,7 +13,7 @@ Pod::Spec.new do |s| 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 diff --git a/Tests/SwiftXMLParserTests/SwiftXMLParserTests.swift b/Tests/SwiftXMLParserTests/SwiftXMLParserTests.swift index 15041a2..a9e87b4 100644 --- a/Tests/SwiftXMLParserTests/SwiftXMLParserTests.swift +++ b/Tests/SwiftXMLParserTests/SwiftXMLParserTests.swift @@ -91,3 +91,163 @@ class SwiftXMLParserTests: XCTestCase { XCTAssertTrue(xml.count > 0) } } + + +extension SwiftXMLParserTests { + func testRepeatedElementsPreserveOrder() { + let result = SwiftXMLParser.makeDic(string: "onetwothree") + let root = result?["root"] as? [String: Any] + XCTAssertEqual(root?["item"] as? [String], ["one", "two", "three"]) + } + + func testRepeatedNestedElementsPreserveChildrenAndAttributes() { + let result = SwiftXMLParser.makeDic(string: "onetwo") + let root = result?["root"] as? [String: Any] + let items = root?["item"] as? [[String: Any]] + XCTAssertEqual(items?.count, 2) + XCTAssertEqual(items?.first?["name"] as? String, "one") + XCTAssertEqual(items?.last?["name"] as? String, "two") + XCTAssertEqual(items?.first?["_XMLAttributes"] as? [String: String], ["id": "1"]) + XCTAssertEqual(items?.last?["_XMLAttributes"] as? [String: String], ["id": "2"]) + } + + func testTextAndAttributes() { + let parser = SwiftXMLParser() + let result = parser.makeDic(data: Data("value".utf8)) + let item = result?["item"] as? [String: Any] + XCTAssertEqual(item?[parser.AttributesKey] as? [String: String], ["id": "1"]) + XCTAssertEqual(item?[parser.TextKey] as? String, "value") + } + + func testFlattenedAttributes() { + let parser = SwiftXMLParser() + parser.attributesAsStandaloneDic = false + let result = parser.makeDic(data: Data("value".utf8)) + let item = result?["item"] as? [String: Any] + XCTAssertEqual(item?["id"] as? String, "1") + XCTAssertEqual(item?[parser.TextKey] as? String, "value") + XCTAssertNil(item?[parser.AttributesKey]) + } + + func testParserCanBeReused() { + let parser = SwiftXMLParser() + XCTAssertEqual(parser.makeDic(data: Data("one".utf8))?["first"] as? String, "one") + let second = parser.makeDic(data: Data("two".utf8)) + XCTAssertNil(second?["first"]) + XCTAssertEqual(second?["second"] as? String, "two") + } + + func testMalformedAndEmptyInput() { + XCTAssertNil(SwiftXMLParser.makeDic(string: "")) + XCTAssertNil(SwiftXMLParser.makeDic(data: Data())) + } + + func testEmptyElementsDoNotRemoveNonemptySiblings() { + let result = SwiftXMLParser.makeDic(string: "one") + let root = result?["root"] as? [String: Any] + XCTAssertEqual(root?["item"] as? String, "one") + XCTAssertNil(root?["empty"]) + } + + func testSerializationUsesCDATAAndResetsState() { + let parser = SwiftXMLParser() + XCTAssertEqual(parser.makeXML(dic: ["root": ["item": ["one", "two"]]]), + "") + XCTAssertEqual(parser.makeXML(dic: ["root": ["item": "three"]]), + "") + } +} + + +extension SwiftXMLParserTests { + func testCDATAContentsArePreserved() { + let result = SwiftXMLParser.makeDic(string: " & 你好 😀 ]]>") + XCTAssertEqual(result?["root"] as? String, " Hello & 你好 😀 ") + } + + func testAdjacentCDATABlocksAreCombined() { + let result = SwiftXMLParser.makeDic(string: "") + XCTAssertEqual(result?["root"] as? String, "first second") + } + + func testSerializedElementOnlyDocumentRoundTrips() { + // The dictionary model supports element-only documents, not mixed + // text-and-child content. Exercise the serializer's own CDATA output. + let original: [String: Any] = [ + "root": [ + "_XMLAttributes": ["id": "example"], + "item": ["one", " two & ", "你好 😀"] + ] + ] + let xml = SwiftXMLParser.makeXML(dic: original) + let decoded = SwiftXMLParser.makeDic(string: xml) + XCTAssertNotNil(decoded) + XCTAssertEqual(decoded as NSDictionary?, original as NSDictionary) + } +} + + +extension SwiftXMLParserTests { + func testRepeatedTextElementsKeepTheirOwnAttributes() { + let parser = SwiftXMLParser() + let result = parser.makeDic(data: Data("onetwo".utf8)) + let items = (result?["root"] as? [String: Any])?["item"] as? [[String: Any]] + XCTAssertEqual(items?.count, 2) + XCTAssertEqual(items?.first?[parser.AttributesKey] as? [String: String], ["id": "1"]) + XCTAssertEqual(items?.last?[parser.AttributesKey] as? [String: String], ["id": "2"]) + XCTAssertEqual(items?.first?[parser.TextKey] as? String, "one") + XCTAssertEqual(items?.last?[parser.TextKey] as? String, "two") + } + + func testAttributeOnlyElementIsRetained() { + let result = SwiftXMLParser.makeDic(string: "") + let item = (result?["root"] as? [String: Any])?["item"] as? [String: Any] + XCTAssertEqual(item?["_XMLAttributes"] as? [String: String], ["id": "1"]) + } + + func testSameNamedNestedElementsRemainSeparate() { + let result = SwiftXMLParser.makeDic(string: "inner") + let outer = (result?["root"] as? [String: Any])?["item"] as? [String: Any] + XCTAssertEqual(outer?["item"] as? String, "inner") + } + + func testEscapedXMLCharactersAreDecoded() { + let result = SwiftXMLParser.makeDic(string: "<tag>&"'") + XCTAssertEqual(result?["root"] as? String, "&\"'") + } + + func testInvalidXMLVariantsAreRejected() { + for input in ["", "", "", "", "oktrailing", "plain text", " \n\t"] { + XCTAssertNil(SwiftXMLParser.makeDic(string: input), "Accepted invalid XML: \(input)") + } + XCTAssertNil(SwiftXMLParser.makeDic(data: Data([0xFF, 0xFF, 0x00]))) + } + + func testParserRecoversAfterFailedParseAndKeepsAttributeMode() { + let parser = SwiftXMLParser() + parser.attributesAsStandaloneDic = false + XCTAssertNil(parser.makeDic(data: Data("old".utf8))) + let result = parser.makeDic(data: Data("new".utf8)) + let root = result?["root"] as? [String: Any] + XCTAssertEqual(root?["id"] as? String, "2") + XCTAssertEqual(root?["item"] as? String, "new") + XCTAssertNil(root?[parser.AttributesKey]) + XCTAssertNil(result?["broken"]) + } + + func testUTF8DeclarationAndBOM() { + let xml = "" + var bytes = Data([0xEF, 0xBB, 0xBF]) + bytes.append(Data(xml.utf8)) + XCTAssertEqual(SwiftXMLParser.makeDic(data: bytes)?["root"] as? String, "你好 😀") + } +} + + +extension SwiftXMLParserTests { + func testValidEmptyRootIsNotConfusedWithMissingRoot() { + let result = SwiftXMLParser.makeDic(string: "") + XCTAssertNotNil(result) + XCTAssertTrue(result?.isEmpty == true) + } +} diff --git a/scripts/test-consumer.sh b/scripts/test-consumer.sh new file mode 100755 index 0000000..6f5a3e4 --- /dev/null +++ b/scripts/test-consumer.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -euo pipefail +repo_root=$(cd "$(dirname "$0")/.." && pwd) +consumer_dir=$(mktemp -d "${TMPDIR:-/tmp}/SwiftXMLParserConsumer.XXXXXX") +trap 'rm -rf "$consumer_dir"' EXIT +version=${PACKAGE_VERSION:-} +python3 - "$repo_root" "$consumer_dir" "$version" <<'PY' +import json, pathlib, re, sys +root, destination, version = sys.argv[1:] +if version and not re.fullmatch(r"\d+\.\d+\.\d+", version): + raise SystemExit("Expected a semantic version tag") +dependency = '.package(url: "https://github.com/100mango/SwiftXMLParser.git", .exact("' + version + '"))' if version else '.package(path: ' + json.dumps(root, ensure_ascii=False) + ')' +p = pathlib.Path(destination) +(p / 'Sources/Consumer').mkdir(parents=True) +(p / 'Package.swift').write_text('''// swift-tools-version:5.3 +import PackageDescription +let package = Package( + name: "Consumer", + products: [.executable(name: "Consumer", targets: ["Consumer"])], + dependencies: [''' + dependency + '''], + targets: [.target(name: "Consumer", dependencies: [.product(name: "SwiftXMLParser", package: "SwiftXMLParser")])] +) +''') +PY +cat > "$consumer_dir/Sources/Consumer/main.swift" <<'SWIFT' +import Foundation +import SwiftXMLParser + +let original: [String: Any] = ["root": ["_XMLAttributes": ["id": "consumer"], "item": ["one", " two & ", "你好 😀"]]] +let xml = SwiftXMLParser.makeXML(dic: original) +guard let result = SwiftXMLParser.makeDic(string: xml) else { fatalError("Serialized XML did not parse") } +precondition(NSDictionary(dictionary: result) == NSDictionary(dictionary: original)) +let parser = SwiftXMLParser() +parser.attributesAsStandaloneDic = false +let flat = parser.makeDic(data: Data("value".utf8)) +let item = flat?["item"] as? [String: Any] +precondition(item?["id"] as? String == "1") +precondition(item?[parser.TextKey] as? String == "value") +precondition(SwiftXMLParser.makeDic(string: "") == nil) +precondition(SwiftXMLParser.makeDic(string: " \n\t") == nil) +print("External consumer passed: imports, parsing, attributes, CDATA round-trip, and invalid input") +SWIFT +swift package --package-path "$consumer_dir" resolve +if [[ -n "$version" ]]; then + python3 - "$consumer_dir/Package.resolved" "$version" "${EXPECTED_REVISION:-}" <<'PY' +import json, sys +path, version, expected = sys.argv[1:] +data = json.load(open(path)) +pins = data.get('pins', data.get('object', {}).get('pins', [])) +pin = next(p for p in pins if p.get('identity', p.get('package', '')).lower() == 'swiftxmlparser') +assert pin['state']['version'] == version, pin +if expected: + assert pin['state']['revision'] == expected, pin +print('Verified remote version and revision:', pin['state']) +PY +fi +swift run --package-path "$consumer_dir" --configuration release --jobs 2 Consumer