CoreOffice / XMLCoder

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

DynamicNodeEncoding not working on child attribute #218

Open 1n9i9c7om opened 3 years ago

1n9i9c7om commented 3 years ago

Hi,

first of all, thanks for this project. I'm just starting with Swift and so far this library hasn't been hard to understand.

However, I'm having a problem when it comes to encoding an attribute of a child element as an attribute instead of an element.

I can't provide the exact code, but the situation is similar to this:

class A : Codable, DynamicNodeEncoding, DynamicNodeDecoding {
    var attr1: String
    var attr2: Double
    var version: Double

    // CodingKeys, required init(from decoder: Decoder),  override func encode, nodeDecoding

    static func nodeEncoding(for key: CodingKey) -> XMLEncoder.NodeEncoding {
        print("A encoding: \(key.stringValue)")
        switch key {
        case Child.CodingKeys.version: return .attribute
        default: return .element
        }
    }
}
class B : A {
    var child: Child
    // CodingKeys, required init(from decoder: Decoder),  override func encode
}
class Child : Codable, DynamicNodeEncoding, DynamicNodeDecoding {
    var version: Double
    var text: String

    // CodingKeys, etc.

    static func nodeEncoding(for key: CodingKey) -> XMLEncoder.NodeEncoding {
        print("child encoding: \(key.stringValue)")
        switch key {
        case Child.CodingKeys.version: return .attribute
        default: return .element
        }
    }
}

When I encode an instance of class B, I can see that A.nodeEncoding is being called. However, Child.nodeEncoding is never called and version is being added as an element instead of an attribute:

<message version="1.0">
    <attr1>Hello World!</attr1>
    <attr2>3.141</attr2>
    <child>
        <version>123.4</version>
        <text>I'm not a cat.</text>
    </child>
</message>

While I'd expect the following output:

<message version="1.0">
    <attr1>Hello World!</attr1>
    <attr2>3.141</attr2>
    <child version="123.4">
        <text>I'm not a cat.</text>
    </child>
</message>

Am I doing something wrong?