XML-Groovy.xml.groovy 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * Available context bindings:
  3. * COLUMNS List<DataColumn>
  4. * ROWS Iterable<DataRow>
  5. * OUT { append() }
  6. * FORMATTER { format(row, col); formatValue(Object, col) }
  7. * TRANSPOSED Boolean
  8. * plus ALL_COLUMNS, TABLE, DIALECT
  9. *
  10. * where:
  11. * DataRow { rowNumber(); first(); last(); data(): List<Object>; value(column): Object }
  12. * DataColumn { columnNumber(), name() }
  13. */
  14. import java.util.regex.Pattern
  15. NEWLINE = System.getProperty("line.separator")
  16. pattern = Pattern.compile("[^\\w\\d]")
  17. def escapeTag(name) {
  18. name = pattern.matcher(name).replaceAll("_")
  19. return name.isEmpty() || !Character.isLetter(name.charAt(0)) ? "_$name" : name
  20. }
  21. def printRow = { values, rowTag, namer, valueToString ->
  22. OUT.append("$NEWLINE<$rowTag>$NEWLINE")
  23. values.eachWithIndex { it, index ->
  24. def tag = namer(it, index)
  25. def str = valueToString(it)
  26. OUT.append(" <$tag>$str</$tag>$NEWLINE")
  27. }
  28. OUT.append("</$rowTag>")
  29. }
  30. OUT.append(
  31. """<?xml version="1.0" encoding="UTF-8"?>
  32. <data>""")
  33. if (!TRANSPOSED) {
  34. ROWS.each { row -> printRow(COLUMNS, "row", {it, _ -> escapeTag(it.name())}) { FORMATTER.format(row, it) } }
  35. }
  36. else {
  37. def values = COLUMNS.collect { new ArrayList<String>() }
  38. ROWS.each { row -> COLUMNS.eachWithIndex { col, i -> values[i].add(FORMATTER.format(row, col)) } }
  39. values.eachWithIndex { it, index -> printRow(it, escapeTag(COLUMNS[index].name()), { _, i -> "row${i + 1}" }, { it }) }
  40. }
  41. OUT.append("""
  42. </data>
  43. """)