java - Groovy script xml parser for multiple files -


hi groovy script strips out xml tag file , writes file.

 import org.apache.commons.lang.randomstringutils  import groovy.util.xmlslurper     inputfile = 'c:\\sample.xml'  outputfile = 'c:\\ouput.txt'    xmltag='details'   filecontents = new file(inputfile).gettext('utf-8')   def xmlfile=new xmlslurper().parsetext(filecontents)   def mypayload= new string(xmlfile.'**'.find{node-> node.name() ==    xmltag}   *.text().tostring())    file = new file(outputfile)  w = file.newwriter()   w << mypayload.substring(1, mypayload.length()-1)  w.close() 

my question how write goes through entire directory , performs on multiple xml files , creates multiple output @ moment hard coded. ('c:\sample.xml' , 'c:\ouput.txt')

thanks

leon

first, recommend take have , put single function; it's coding practrice , improves readabililty.

now executing function on each xml file in directory, can use groovy's file.eachfilematch(). example, if want run on each xml file in current directory, do:

import org.apache.commons.lang.randomstringutils import groovy.util.xmlslurper import static groovy.io.filetype.*  void striptag(file inputfile, string outputfile) {     def xmltag='details'      filecontents = inputfile.gettext('utf-8')      def xmlfile=new xmlslurper().parsetext(filecontents)      def mypayload= new string(xmlfile.'**'.find{node-> node.name() == xmltag}*.text().tostring())       def file = new file(outputfile)     w = file.newwriter()      w << mypayload.substring(1, mypayload.length()-1)     w.close() }  // match files in current directory file extension .xml new file(".").eachfilematch(files, ~/.*\.xml/) { file input ->     // set output file name <file_name>_out.txt     // change need     striptag(input, input.name + "_out.txt") } 

if want to, can add reading in directory command line well.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -