Anyone with experience using xml util (<https://gi...
# serialization
r
Anyone with experience using xml util (https://github.com/pdvrieze/xmlutil) know if it's possible to set my tag name and element text based on properties of my class? More in 🧵
I have a model that more or less mimics the XML structure it gets serialized to e.g.
Copy code
data class Model(
    name: String = "default",
    text: String = "",
    attributes: Map<String, String> = emptyMap(),
    children: Collection<Model> = emptyList()
)
Given an instance like this:
Copy code
val model = Model(
    name = "parent",
    attributes = mapOf("attribute" to "value"),
    children = listOf(
        Model(
            name = "child",
            text = "child text"
        )
    )
)
The xml would look like:
Copy code
<parent attribute="value">
  <child>child text</child>
</parent>
Is is possible to achieve this type of content-based serialization with xmlutil?
a
I have used xmlutil for a project recently but I am certainly not a definitive expert... I believe it isn't impossible but may be quite difficult. Starting point would be here to see how some tag names (and attributes too, I assume) can be created dynamically with a custom serializer. If your element and attribute names are entirely dynamic this may the the only option however if you have a predetermined list of possible values (like an enum), creating a sealed class then classes for all the individual options with simple annotations may be a lot easier. If you will also be de-serializing, you'll have to consider how to recognize the dynamic tag/attribute names and then convert them to the generic
Model
.
r
Good points all around. I've been reading through the dynamic tag names example and this use case seems to be quite difficult as you said. Unfortunately, there is not a predetermined set of possible values. This particular model is meant to be extensible for application-specific detail, otherwise your enum + sealed type suggestion would be a good fit and I'd get polymorphic serialization for free from xmlutil. I recently stumbled on
@XmlOtherAttributes
, which has helped significantly because it takes care of
Model::attributes
.
Model::children
is handled inherently, so it's just down to the dynamic names and text and I think
XmlDelegatingTagWriter
might be the only way.