Groovy web console

subscribe to the feed Subscribe
to this
site
xml to json (via #groovywebconsole)
tweet this snippet Tweet
this
script

xml to json

Published 1 month ago by nmrao with tags convert
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def xml = """<Results>
      <ResultSet fetchSize="10">
            <Row rowNumber="1">
                   <ORDERID>H001</ORDERID>
                   <LINEID>L001</LINEID>
                   <HOLDID>1</HOLDID>
                   <HOLDNAME>HOLDA</HOLDNAME>
                   <RELEASED_FLAG>N</RELEASED_FLAG>
            </Row>
            <Row rowNumber="2">
                   <ORDERID>H001</ORDERID>
                   <LINEID>L001</LINEID>
                   <HOLDID>2</HOLDID>
                   <HOLDNAME>HOLDB</HOLDNAME>
                   <RELEASED_FLAG>N</RELEASED_FLAG>
            </Row>
            <Row rowNumber="3">
                   <ORDERID>H001</ORDERID>
                   <LINEID>3</LINEID>
                   <HOLDID>3</HOLDID>
                   <HOLDNAME>HOLDC</HOLDNAME>
                   <RELEASED_FLAG>N</RELEASED_FLAG>
            </Row>
      </ResultSet>
</Results>"""

def parsed = new XmlSlurper().parseText(xml)
def map = ['requestPayload' :  parsed.'**'.findAll{it.name() == 'Row'}.collect{element -> element.children().breadthFirst()*.name()
             .findAll { !element."$it".children().size() }
           .collectEntries{[(element."$it".name()): element."$it".text()] }
}]

println new groovy.json.JsonBuilder(map).toPrettyString()