pdvrieze / xmlutil

XML Serialization library for Kotlin
https://pdvrieze.github.io/xmlutil/
Apache License 2.0
363 stars 30 forks source link

Enums as XML attributes #175

Closed zelitomas closed 10 months ago

zelitomas commented 10 months ago

Hello,

thanks for amazing library! One thing I'm missing though is ability to use serialize Kotlin Enums as XML attributes.

For example, here is the XML I need to send to one of APIs I interact with:

<Code q2:type="EAN13">1234567890123</Code>

It seems to me that I only have 2 options:

<Code>
   <q2:type>EAN13</q2:type>
   <q2:value>1234567890123</q2:value>
</Code>

Is there any elegant way that I am missing how to make enum XML attributes?

Edit: Typos

pdvrieze commented 10 months ago

It should be enough to use @XmlElement(false) on the type attribute. If that doesn't work it is a bug in the default policy (making your own policy could fix that). Unfortunately changing the default for enums would be a problem at this point as it would break existing code/serial formats.

zelitomas commented 10 months ago

Thanks for your help! @XmlElement(false) really did help. Speaking of policies - is there any place (documentation perhaps) where I can learn about how to write / modify these?

Thank you once again for the @XmlElement(false)

pdvrieze commented 10 months ago

As I'm primarily a full-time academic the documentation is somewhat limited. The policy is basically an interface that can be assigned in the configuration (when creating an XML object). There is a default implementation (DefaultXmlSerializationPolicy) that itself is somewhat configurable but can be overridden for specific behaviour. There is an example that mimics the Jackson strategy.

The concept is that rather than deciding how to serialize/structure things this is done by asking the policy. Important to consider here is that the serialization/deserialization works in two stages. First a tree of XmlDescriptors is created that will guide the serialization/deserialization. It is at this stage that the "structure" of the document is decided based on the policy. This structure is then used to actually serialize/deserialize. (the reason for this approach is to ensure consistency and reduce complexity in the encoder/decoders).

Many of the functions in the policy will give you access to (partial) descriptors and "parent" information. This is somewhat restricted as this is done during the building of the tree, so recursion issues must be avoided (eg. looking up the resolved children of a tag while deciding one of these children - you will have access to the underlying SerialDescriptor - just not the augmented descriptor).