anon
anon

Reputation:

Parsing XML with multi-line records

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()

Upvotes: 1

Views: 4063

Answers (3)

Kornel
Kornel

Reputation: 100170

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

Upvotes: 0

jfs
jfs

Reputation: 240

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.

Upvotes: 0

mbrevoort
mbrevoort

Reputation: 5165

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()
}

Upvotes: 1

Related Questions