CoreOffice / XMLCoder

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

How to encode as an empty element #177

Closed ksoftllc closed 4 years ago

ksoftllc commented 4 years ago

I have a need to output an empty element, such as the PhoneNumbers element in this example:

<Person>
    <FirstName><![CDATA[BART]]></FirstName>
    <LastName><![CDATA[SIMPHSON]]></LastName>
    <Address1><![CDATA[122 ELMARCH AVE, CYNTHIANA, KY, 41031]]></Address1>
    <City><![CDATA[CYNTHIANA]]></City>
    <Zip><![CDATA[41031]]></Zip>
    <BirthDate><![CDATA[1950-05-01]]></BirthDate>
    <PhoneNumbers />
</Person>

Here is the struct:

struct Person: Encodable {
    let FirstName: String
    //. . .
    let PhoneNumbers: ???? //what goes here?
    //. . .
}

struct PhoneNumber: Encodable {
    let type: Int
    let number: String
}

I have tried the following values, but none appear in the encoded XML at all:

    let PhoneNumbers: [PhoneNumber] = []()
    let PhoneNumbers: [PhoneNumber]? = nil

I want the encoded XML to include the PhoneNumber element even when empty. Is that possible? If so, how?

Thanks!

MaxDesiatov commented 4 years ago

Hey @ksoftllc, have you tried something like this?

struct Person: Encodable {
    //. . .
    let PhoneNumbers: PhoneNumbers
    //. . .
}

struct PhoneNumbers: Encodable {
    enum CodingKeys: String, CodingKey { case items = "PhoneNumber" }
    let items: [PhoneNumber]
}

struct PhoneNumber: Encodable {
    let type: Int
    let number: String
}

This assumes that elements contained within a non-empty PhoneNumbers element are called PhoneNumber, I hope the code can be easily adjusted otherwise.

Does that resolve your issue?

ksoftllc commented 4 years ago

That was the key. Problem solved. Thanks Max. Nice utility.