用于多个文件的java Groovy脚本xml解析器
嗨,我的groovy脚本从一个文件中去掉一个xml标记并写入一个文件
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()
我的问题是,我该如何编写它,使它遍历整个目录,并在多个xml文件上执行它,并创建多个输出,就像目前它是硬编码的一样。('C:\sample.xml'和'C:\output.txt')
谢谢
里昂
# 1 楼答案
首先,我建议你把你拥有的东西放到一个单一的函数中;这是很好的编码实践,提高了可读性
现在,要对目录中的每个xml文件执行该函数,可以使用groovy的File.eachFileMatch()。例如,如果要在当前目录中的每个xml文件上运行它,可以执行以下操作:
如果需要,也可以从命令行在目录中添加读取