Create an Xml from Linkedhash Map

44 Views Asked by At

We have requirement where from this LinkeedhashMap we need to create an XMl

[Type:[eq '02', eq '01'], Value:[eq '22'], (Date:[ge datetime'2023-02-28T00:00:00'], Date:[le datetime'2023-03-01T00:00:00')]]

Expected Output:

<filter>
    <expression>
        <leftOperand>Type</leftOperand>
        <operator>eq</operator>
        <rightOperand>02</rightOperand>
    </expression>
    <expression>
        <leftOperand>Type</leftOperand>
        <operator>eq</operator>
        <rightOperand>01</rightOperand>
    </expression>
    <expression>
        <leftOperand>Value</leftOperand>
        <operator>eq</operator>
        <rightOperand>22</rightOperand>
    </expression>
    <expression>
        <leftOperand>Date</leftOperand>
        <operator>ge</operator>
        <rightOperand>2023-02-28T00:00</rightOperand>
    </expression>
    <expression>
        <leftOperand>Date</leftOperand>
        <operator>le</operator>
        <rightOperand>2023-03-01T00:00</rightOperand>
    </expression>
</filter>

it be achieved by XSLT or Groovy script?

1

There are 1 best solutions below

0
IWilms On

I can only offer Groovy support. It is not entirely clear to me what the data types in your Map are, but if your Map is like this:

Map map = [Type: ["eq '02'", "eq '01'"], Value: ["eq '22'"], Date: ["ge datetime'2023-02-28T00:00:00'"], Date: ["le datetime'2023-03-01T00:00:00'"]]

you could use Groovy's StreamingMarkupBuilder to create your XML like so:

import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil

def xmlBuilder = new StreamingMarkupBuilder()
def writer = xmlBuilder.bind {
    filter {
        map.each { left, ops ->
            ops.each {
                def (op, right) = it.split()
                expression {
                    leftOperand left
                    operator op
                    rightOperand((right =~ /'(.*)'/)[0][1])
                }
            }
        }
    }
}
println(XmlUtil.serialize(writer.toString()))