tags:

views:

1245

answers:

3

I'd like to take XML in the format below and load each code record into a domain object in my BootStrap.groovy. I want to preserve the formatting of each snippet of code.

XML

<records>
    <code>
        <language>Groovy</language>
        <snippet>
            println "This is Groovy"
            println "A very powerful language"
        </snippet>
    </code>
    <code>
        <language>Groovy</language>
        <snippet>
            3.times {
                println "hello"
            }
        </snippet>
    </code>
    <code>
        <language>Perl</language>
        <snippet>
            @foo = split(",");
        </snippet>
    </code>
</records>

Domain Object

Code {
    String language
    String snippet
}

BootStrap.groovy

new Code(language l, snippet: x).save()
+1  A: 

roughly something like this:

def CODE_XML = '''
<records>
    <code>
        <language>Groovy</language>
        <snippet>
            println "This is Groovy"
            println "A very powerful language"
        </snippet>
    </code>
    <code>
        <language>Groovy</language>
        <snippet>
            3.times {
                println "hello"
            }
        </snippet>
    </code>
    <code>
        <language>Perl</language>
        <snippet>
            @foo = split(",");
        </snippet>
    </code>
</records>
  '''
def records = new XmlParser().parseText(CODE_XML)
records.code.each() { code ->
    new Code(language: code.language, snippet: code.snippet).save()
}
mbrevoort
A: 

If you can specity a DTD or similar and your XML parser obeys it, I think you can specify the contents of the snippet element to be CDATA and always get it as-is.

jfs
A: 

Try adding xml:space="preserve" attribute to <snippet> elements.

porneL