redundent / kotlin-xml-builder

A lightweight type safe builder to build xml documents in Kotlin
Apache License 2.0
155 stars 19 forks source link

[Question] Support for optionals? #27

Closed SirWellington closed 5 years ago

SirWellington commented 5 years ago

Is there any way to use this library with optional elements. So for example, if I have a name element that should be added only if the field is optional?

data class Person(val firstName: String, val lastName: String?)

lastName=Smith

<Person>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Person>

lastName=null

<Person>
<FirstName>John</FirstName>
</Person>
redundent commented 5 years ago

Hey @SirWellington ,

You can achieve that by just wrapping the LastName element in an if.

xml("Person") {
    "FirstName"(person.firstName)
    if (person.lastName != null) {
        "LastName"(person.lastName)
    }
}

Or fancier

xml("Person") {
    "FirstName"(person.firstName)
    person.lastName?.run { "LastName"(this) }
}

Does that answer your question?

SirWellington commented 5 years ago

@redundent – Works for me!