pdvrieze / xmlutil

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

[UnknownXmlFieldException] How to ignore unspecified fields when deserializing? #257

Closed Rashxz closed 3 days ago

Rashxz commented 3 days ago

Hi, Im tryng to deserialze a xml response that have a lot of fields, but I will only be using a few, so dont what to specify all of them as that will be time consuming and having only necesary fields will make it easier to read.

This is my class:

@Serializable
@XmlSerialName("Z_WEBCOM_CONSULTAResponse", "urn:sap-com:document:sap:rfc:functions", "n0")
data class SearchOrdersDTO(
    @XmlSerialName("CLIENTES", "", "")
    @XmlElement(true)
    val clients: ClientsSection,

    @XmlSerialName("TVBAK", "", "")
    @XmlElement(true)
    val tvBak: TvBakSection,
){
    @Serializable
    data class ClientsSection(
        @XmlSerialName("item", "", "")
        @XmlElement(true)
        val items: List<ClientDataItem>
    ){
        @Serializable
        data class ClientDataItem(
            @XmlSerialName("KUNNR", "", "")
            @XmlElement(true)
            val clientCode: String,

            @XmlSerialName("NAME1", "", "")
            @XmlElement(true)
            val name: String,
        )
    }
}

If i put all of the fields of ClientDataItem the deserialization works just fine, but if I only leave a fews I got the UnknownXmlFieldException exception. So is there anyway to just ignore the rest of fields when deserializing?

pdvrieze commented 3 days ago

In the policy you can add a handler for unknown fields/elements. This returns a list of the recovered values (which can be an empty list) or throws an exception (the default). However, see #256, there is an issue with it in the case of a value child (the @XmlValue annotation).

pdvrieze commented 3 days ago

An alternate approach is to use the fallback options (@XmlOtherAttributes with either Map<QName,String> or Map<String,String> - the string is default, but it should work for anything that can parse from a string), and for elements an @XmlValue List<Node> or List<Element> (or other type with a serializer implementing XmlDeserializationStrategy (this needed to consume the random xml)).

This approach will actually record the values in a generic way (which can be written out).

Rashxz commented 3 days ago

Thanks, the policy works perfectly.