-1

I'm a newbie in groovy Can anyone help to parse this xml in order to get a list of values of the each num element

 NAMES>
    <NAMESet fetchSize="3">
    <String StringNumber="1">
        <NUM>1</NUM>
    </String>
    <String StringNumber="2">
        <NUM>2</NUM>
    </String>
    <String StringNumber="3">
        <NUM>3</NUM>
</NAMESet>

thanks in advance!

Will
  • 14,348
  • 1
  • 42
  • 44
Leo
  • 1,787
  • 5
  • 21
  • 43
  • 3
    Hey, [google is your friend](https://encrypted.google.com/search?hl=en&q=groovy%20parse%20xml). Did you tried the [first link](http://groovy.codehaus.org/Reading+XML+using+Groovy%27s+XmlSlurper)? It is the official doc for groovy and xml. If you got problems with that, post some info on what happened. – Will Oct 13 '14 at 14:14
  • 3
    Also that XML looks pretty broken. Is that the problem? – Will Oct 13 '14 at 14:15
  • 3
    Also show us your code so far – cfrick Oct 13 '14 at 14:17
  • yeah, I've checked that. I coudn't catch how to get a value of one of the NUM nodes – Leo Oct 13 '14 at 14:35
  • 2
    Post the code you tried – Will Oct 13 '14 at 14:47
  • there is just one line: def records = new XmlParser().parseText(xml) – Leo Oct 13 '14 at 15:50

2 Answers2

0

The XML is pretty broken, but cyberneko can solve that. It builds up some HTML structure, though:

xml=''' NAMES>
    <NAMESet fetchSize="3">
    <String StringNumber="1">
        <NUM>1</NUM>
    </String>
    <String StringNumber="2">
        <NUM>2</NUM>
    </String>
    <String StringNumber="3">
        <NUM>3</NUM>
</NAMESet>'''


names = new XmlSlurper( new org.cyberneko.html.parsers.SAXParser() ).parseText xml

assert names.BODY.NAMESET.STRING.NUM.collect { it.text() } == 
    ['1', '2', '3']
Will
  • 14,348
  • 1
  • 42
  • 44
0

finally, wrote like this:

def records = new XmlParser().parseText(xml)
def size = records.ResultSet.Row.ID.size()
println(size)
def allRecords = records.ResultSet.Row.ID[1].text()
println(allRecords)
for (int i = 0; i < size; i++) {
println(records.ResultSet.Row.ID[i].text())
}

anyway, thanks

Leo
  • 1,787
  • 5
  • 21
  • 43