Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy > Nested Map to Xml

Tags:

xml

groovy

I'd like to convert my Map object to Xml in Groovy. I've had a look around at the current examples, and I thought this would be much simpler!

All samples I've found, either use a MarkupBuilder to manually specify the fields, or have a utility method to iterate over the tree. Most heinous!

Is there something I'm missing? I can convert these other formats simply enough...

JsonOutput.prettyPrint(JsonOutput.toJson(map))    // json
(map as ConfigObject).writeTo(new StringWriter()) // groovy
new Yaml().dump(map, new StringWriter())          // yml

Why can't I just do?

XmlUtil.serialize(map)

(OR How can I cast my Map object to a Element/Node/GPathResult/Writable object?)

Groovy Sample Code

def myMap = [
    key1: 'value1',
    key2: 'value2',
    key3: [
        key1: 'value1',
        key2: 'value2',
        key3: [
            key1: 'value1',
            key2: 'value2',
        ]
    ]
]

Preferred output

<root>
    <key1>value1</key1>
    <key2>value2</key2>
    <key3>
        <key1>value1</key1>
        <key2>value2</key2>
        <key3>
            <key1>value1</key1>
            <key2>value2</key2>
        </key3>
    </key3>
</root>
like image 542
Nick Grealy Avatar asked Jun 23 '15 08:06

Nick Grealy


1 Answers

You can do:

import groovy.xml.*

new StringWriter().with { sw ->
    new MarkupBuilder(sw).with {
        root { 
            myMap.collect { k, v ->
                "$k" { v instanceof Map ? v.collect(owner) : mkp.yield(v) }
            }
        }
    }
    println sw.toString()
}

To output:

<root>
  <key1>value1</key1>
  <key2>value2</key2>
  <key3>
    <key1>value1</key1>
    <key2>value2</key2>
    <key3>
      <key1>value1</key1>
      <key2>value2</key2>
    </key3>
  </key3>
</root>

There's no magic method you can call that I'm aware of (probably because due to attributes, there's no magic map -> xml conversion that can be done without knowing the required output structure)

like image 200
tim_yates Avatar answered Oct 16 '22 15:10

tim_yates