xmlutil
xmlutil copied to clipboard
possible to remove tags representing class wrapper (flatten)?
I have a nested structure such that a property of my main class is a sub-class. By default, during serialization the sub-class creates a tag even when it has no attributes. My goal is to flatten this structure by eliminating the <MessageDate> tags and just have <Year> <Month> and <Day> be immediate children of <MyMessage> (and siblings of <MessageText>)
Can this be done with an annotation (best option) or policy, or a custom serializer? I will also want to be able to de-serialize XML strings with a flatter structure than my class hierarchy.
Thank you very much!
@Serializable
data class MyMessage (
val SenderID: String,
val SendDate: MessageDate,
@XmlElement(true) val MessageText: String
)
@Serializable
data class MessageDate ( // has no attributes, goal is to eliminate the <MessageDate> tag
@XmlElement(true) val Year : Int,
@XmlElement(true) val Month : Int,
@XmlElement(true) val Day : Int,
)
val hal9000 = MyMessage("HAL9000", MessageDate(1992, 1, 12), "I am completely operational, and all my circuits are functioning perfectly.")
fun makeHal() = xml.encodeToString(MyMessage.serializer(), hal9000).also { println(it) }
default output:
<MyMessage SenderID="HAL9000">
<MessageDate>
<Year>1992</Year>
<Month>1</Month>
<Day>12</Day>
</MessageDate>
<MessageText>I am completely operational, and all my circuits are functioning perfectly.</MessageText>
</MyMessage>
desired output:
<MyMessage SenderID="HAL9000">
<Year>1992</Year>
<Month>1</Month>
<Day>12</Day>
<MessageText>I am completely operational, and all my circuits are functioning perfectly.</MessageText>
</MyMessage>