Groovy> Nested Map in Xml

I would like to convert my object Mapin Xml to Groovy. I reviewed the current examples, and I thought it would be much easier!

All the samples I found either use a MarkupBuilderto manually specify the fields , or have a utility method before iterating through the tree . The most disgusting!

Is there something I am missing? I can convert these other formats quite simply ...

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 it?

XmlUtil.serialize(map)

(OR How can I overlay an object Mapon an object Element/ Node/ GPathResult/ Writable?)

Groovy Sample Code

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

Preferred Exit

<root>
    <key1>value1</key1>
    <key2>value2</key2>
    <key3>
        <key1>value1</key1>
        <key2>value2</key2>
        <key3>
            <key1>value1</key1>
            <key2>value2</key2>
        </key3>
    </key3>
</root>
+4
source share
1 answer

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()
}

:

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

, , (, - magic map β†’ xml, , )

+6

All Articles