You can do it all with basic Groovy:
// Given an XML string
def xml = ‘’’
| Tim
| Tom
|’’’.stripMargin()
// Parse it
def parsed = new XmlParser().parseText( xml )
// Convert it to a Map containing a List of Maps
def jsonObject = [ root: parsed.node.collect {
[ node: it.text() ]
} ]
// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )
// Check it’s what we expected
assert json.toString() == ‘{“root”:[{“node”:“Tim”},{“node”:“Tom”}]}’
HOWEVER, you really need to think about certain things…
How are you going to represent Attributes?
Will your XML contain textwootext style markup? If so, how are you going to handle that?
CDATA? Comments? etc?
It’s not a smooth 1:1 mapping between the two… But for a given specific format of XML, it may be possible to come up with a given specific format of Json.
Update:
To get the names from the document (see comment), you can do:
def jsonObject = [ (parsed.name()): parsed.collect {
[ (it.name()): it.text() ]
} ]
Update 2
You can add support for greater depth with:
// Given an XML string
def xml = ‘’’
| Tim
| Tom
|
| another
|
|’’’.stripMargin()
// Parse it
def parsed = new XmlParser().parseText( xml )
// Deal with each node:
def handle
handle = { node ->
if( node instanceof String ) {
node
}
else {
[ (node.name()): node.collect( handle ) ]
}
}
// Convert it to a Map containing a List of Maps
def jsonObject = [ (parsed.name()): parsed.collect { node ->
[ (node.name()): node.collect( handle ) ]
} ]
// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )
// Check it’s what we expected
assert json.toString() == ‘{“root”:[{“node”:[“Tim”]},{“node”:[“Tom”]},{“node”:[{“anotherNode”:[“another”]}]}]}’
Again, all the previous warnings still hold true (but should be heard a little louder at this point) 