Skip to content

Instantly share code, notes, and snippets.

@loosebits
Last active August 29, 2015 14:12
Show Gist options
  • Save loosebits/aaebe1b8086b5b325670 to your computer and use it in GitHub Desktop.
Save loosebits/aaebe1b8086b5b325670 to your computer and use it in GitHub Desktop.
Converts HTML into Groovy's MarkupBuilder code
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,'')
@loosebits
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment