繁体   English   中英

用于多个文件的Groovy脚本xml解析器

[英]Groovy script xml parser for multiple files

嗨,我的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:\\ 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")
}

如果需要,也可以从命令行在目录中添加阅读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM