Groovy web console

subscribe to the feed Subscribe
to this
site
write data to file from xml (via #groovywebconsole)
tweet this snippet Tweet
this
script

write data to file from xml

Published 7 months ago by nmrao with tags csv
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def xml = """<root xmlns:ns10='url1' xmlns:ns5='url2'> <ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080013</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              <ns10:LocationName>REMOVEDEPENDENCY004</ns10:LocationName>**
             <ns10:RailIncData/>
              <ns10:CustCity333Name>OAKLAND</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
        </ns10:Location>
        <ns10:Location>
           <ns10:LocationId>
              <ns5:RowId>7080018</ns5:RowId>
           </ns10:LocationId>
           <ns10:LocationDetails>
              <ns10:AuditElement/>
              <ns10:EffectiveDate/>
              <ns10:LocationName>REMOVEDEPENDENCY004a</ns10:LocationName>**
              <ns10:RailIncData/>
              <ns10:CustCity333Name>OAKLAND1</ns10:CustCity333Name>**
              <ns10:CustCity333Id>OAKLAND</ns10:CustCity333Id>
              <ns10:CustCity333StateCode>TN</ns10:CustCity333StateCode>
              <ns10:ParentCIFDetails/>
           </ns10:LocationDetails>
</ns10:Location>
</root>"""
def parsedXml = new XmlSlurper().parseText(xml)
def data = parsedXml.'**'.findAll{ it.name() == 'Location'}.inject([]){list, loc -> list << new Expando(
     rowId: loc?.LocationId?.RowId?.text(),
     locationName: loc?.LocationDetails?.LocationName?.text(),
     cityName: loc?.LocationDetails?.CustCity333Name?.text()); list }
if (0< data.size()) {
  def sb = new StringBuffer(data[0].properties.keySet().join(',')).append('\n')
  data.collect { sb.append(it.properties.values().join(',')).append('\n')}
  sb.toString()
} else {
  println 'No records found'
}