Want Groovy MarkupBuilder (), equivalent to JSONBuilder () for objects

Purpose: Given the definition of myInfoObject below, I want to be able to do this:

println new groovy.xml.MarkupBuilder(myInfoObject).toPrettyString()

Prerequisite:
The following is one of Groovy’s most amazing and convenient features for my use cases: brilliant dynamic serialization of complex nested objects into reasonable JSON. Just pass the object and get the JSON.

Example. Simple map on the map.

import groovy.json.*

def myInfoMap = [
    firstname : 'firstname',
    lastname : 'lastname',
    relatives : [
        mother : "mom",
        father : "dad"
 ]
]   
myInfoJson = new JsonBuilder(myInfoMap)

//One line, straight to JSON object, no string writer/parser conversions
//Works on any object, extremely elegant, even handles deep nesting
//Alternatively, add .toPrettyString() for the string representation

Returns:

{
    "firstname": "firstname",
    "lastname": "lastname",
    "relatives": {
        "mother": "mom",
        "father": "dad"
    }
}

I read all the examples and MarkupBuilder documents that I could find, and there seems to be no equivalent for XML. The closest I could find is not the same. http://www.leveluplunch.com/groovy/examples/build-xml-from-map-with-markupbuilder/

XML JSON , , XML . XML , , , , :

<myInfoMap>
  <firstname>firstname</firstname>
  <lastname>lastname</lastname>
  <relatives>
    <relative>
      <mother>mom</mother>
    </relative>
    <relative>
      <father>dad</father>
    </relative>
  </relatives>
</myInfoMap>

... , ...

def writer = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(writer)

builder.myInfoMap {
    myInfoMap.each{key, value ->
        if (value instanceof Map){
            "${key}"{
                value.each{key2, value2 ->
                    "${key[0..key.size()-2]}"{
                        "${key2}" "${value2}"
                    }
                }
            }
        }else{
            "${key}" "${value}"
        }
    }
}
println writer.toString()

, , JSONBuilder, .

, - , JIRA- Groovy . , . , , , .

+4
2

grails.converters.XML. :

def myInfoMap = [
        firstname: 'firstname',
        lastname : 'lastname',
        relatives: [
                mother: "mom",
                father: "dad"
        ]
]

println new grails.converters.XML(myInfoMap)

:

<?xml version="1.0" encoding="UTF-8"?>
<map>
    <entry key="firstname">firstname</entry>
    <entry key="lastname">lastname</entry>
    <entry key="relatives">
        <entry key="mother">mom</entry>
        <entry key="father">dad</entry>
    </entry>
</map>
+1

, , XmlUtil.serialize , , .

MrHaki: groovy -goodness-pretty-print-xml

, , . dns , . xml- gsp- . , - .

+1

Source: https://habr.com/ru/post/1620267/


All Articles