3

I have an XML that looks like this.

<?xml version="1.0" encoding="UTF-8"?>
<header>
<row>
 <item1>stuff</item1>
 <item2>stuff</item2>
</row>
<row>
 <item1>stuff</item1>
 <item2>stuff</item2>
</row>
...
</header>

I want to read this in

def doc = new XmlSlurper().parseText(message)

And then output each "row" element as an individual message. For instance:

<header>
<row1>
     <item1>stuff</item1>
     <item2>stuff</item2>
</row1>
</header>

What is the correct way to do this in Groovy? Should I use an XSLT or is that overcomplicating things?

1 Answer 1

5

If your case is really this simple, I'd go with Groovy which really shines in such scenarios.

final xml = '''
    <header>
        <row>
            <item1>stuff11</item1>
            <item2>stuff12</item2>
        </row>
        <row>
            <item1>stuff21</item1>
            <item2>stuff22</item2>
        </row>
    </header>
'''

final xmlDoc = new XmlSlurper().parseText(xml)

Having read a document, construct a document for each row

def rowId = 1

String singleRow = new StreamingMarkupBuilder().bind {
    header {
        "row$rowId" {
            mkp.yield xmlDoc.row[rowId-1].children()
        }
    }
}

And it's done.

2
  • Hey, thanks for your reply. That looks very straightforward, but two issues. The first is, each row doesn't have an ID, or anything to differentiate it from other rows besides the data inside. The second is, what is mkp.yield?
    – Steve
    Jul 30, 2014 at 17:17
  • @Steve I tried to follow your example, given input and output. Provide an actual example and I'll try to adjust the code. mkp is a special namespace used to escape away from the normal building mode, as explained
    – emesx
    Jul 30, 2014 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.