CoreOffice / XMLCoder

Easy XML parsing using Codable protocols in Swift
https://coreoffice.github.io/XMLCoder/
MIT License
795 stars 107 forks source link

DynamicNodeEncoding doesn't work on root element #194

Closed JamesVanBoxtel closed 3 years ago

JamesVanBoxtel commented 4 years ago

Thanks for the amazing open source project.

While using it I noticed that implementing DynamicNodeEncoding in order to encode a property as an attribute works great for sub elements, but always encodes as an element for the root element.

struct SplitsData: Codable, DynamicNodeEncoding {
    var version: String

    enum CodingKeys: String, CodingKey {
        case version = "version"
    }

    static func nodeEncoding(for key: CodingKey) -> XMLEncoder.NodeEncoding {
        switch key {
        case CodingKeys.version:
            return .attribute
        default:
            return .both
        }
    }
}

let encoder = XMLEncoder()
let encodedRun = try encoder.encode(self.run, withRootKey: "Run", header: XMLHeader(version: 1.0,
    encoding: "UTF-8"))
try encodedRun.write(to: url)

output is something like

<?xml version="1.0" encoding="UTF-8"?>
<Run>
    <version>1.8.0</version>
</Run>
MaxDesiatov commented 4 years ago

Thanks for creating the issue, I'll have a look.

MaxDesiatov commented 4 years ago

@JamesVanBoxtel are you sure you're using the latest version of XMLCoder? I've tried to reproduce the issue in a test, but the version attribute is correctly encoded as an attribute. Could you have a look at that test to verify that I'm not missing anything? Maybe there's something else in your code that could have an impact?

MaxDesiatov commented 3 years ago

With no updates from the OP and no similar reports I'm closing this as stale