嗨,我的时髦脚本从文件中去除一个 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:\ouput.txt")
谢谢
里昂
首先,我建议你把你所拥有的东西放到一个函数中;这是很好的编码练习,提高了可读性。
现在要在目录中的每个xml文件上执行该函数,您可以使用groovy的File.eachFileMatch()。例如,如果要在当前目录中的每个 xml 文件上运行它,则可以执行以下操作:
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()
}
// This will match all files in the current directory with the file extension .xml
new File(".").eachFileMatch(FILES, ~/.*.xml/) { File input ->
// Set the output file name to be <file_name>_out.txt
// Change this as you need
stripTag(input, input.name + "_out.txt")
}
如果需要,您也可以从命令行在目录中添加读取。