Search code examples
xmlkotlinjackson

XML Formatting from Kotlin class


I am trying to format XML from Kotlin data class and I have a problem with attributes. Question is how to add attribute to one field, trying to format something like this:

<ExampleClass>
   <field actionCode="Add">aa</field>
</ExampleClass>

By this:

data class ExampleClass (
    @JacksonXmlProperty(isAttribute = true, localName = "actionCode")
    var fieldActionCode: String = "Add",

    @JacksonXmlProperty(localName = "field")
    var field: String = "aa"
)

But by doing so attribute goes to wrong place, to Example class:

<ExampleClass actionCode="Add">
   <field>aa</field>
</ExampleClass>

I use FasterXML Jackson library.


Solution

  • Attribute goes to correct place since you declare fieldActionCode as an attribute of ExampleClass, not of its nested element.

    Desired output can be achieved like this:

    data class ExampleClass (
        @field:JacksonXmlProperty(localName = "field")
        var field: ExampleField = ExampleField()
    ) {
    
        data class ExampleField(
            @field:JacksonXmlProperty(isAttribute = true, localName = "actionCode")
            var fieldActionCode: String = "Add",
    
            @field:JacksonXmlText
            var field: String = "aa"
        )
    }
    
    fun main() {
        val mapper = XmlMapper().enable(SerializationFeature.INDENT_OUTPUT)
        println(mapper.writeValueAsString(ExampleClass()))
    }
    

    Produces:

    <ExampleClass>
      <field actionCode="Add">aa</field>
    </ExampleClass>