Last active
August 29, 2015 14:12
-
-
Save loosebits/aaebe1b8086b5b325670 to your computer and use it in GitHub Desktop.
Converts HTML into Groovy's MarkupBuilder code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovy.util.XmlSlurper | |
import groovy.util.slurpersupport.* | |
def root = new XmlSlurper().parse(new File(args[0])) | |
def getAttributes(node) { | |
String res = ''; | |
node.attributes().each { key, value -> | |
if (key == 'class') { | |
key = "'class'" | |
} | |
res = res + "$key: '$value', "; | |
} | |
!res ? '': res.substring(0, res.length() - 2) | |
} | |
def groovify(node, indent) { | |
def val = indent | |
if (node.name()) { | |
def text = node.localText() | |
def forceCloseTag = ['script','style'].contains(node.name()) && !text | |
def args = text || forceCloseTag ? "'''${ text[0]?: ''} '''" : '' | |
def attrs = getAttributes(node) | |
if (attrs) { | |
args = attrs + (args || forceCloseTag? ", $args" : '') | |
} | |
if (args) { | |
val = indent + "${node.name()}($args) {\n" | |
} else { | |
val = indent + "${node.name()} {" | |
} | |
val = indent + "${node.name()}($args) {\n" | |
node.childNodes().each { | |
val += groovify(it, indent + ' ') | |
} | |
val += indent + '}\n' | |
} | |
val; | |
} | |
println groovify(root,'') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't handle mixed content (e.g
<div><span class='gyphicon glyphicon-remove'></span>Some text</div>
), can't figure out how to get the node order in those cases. Special (and annoying handling) for empty span tags and empty script tags.