【问题标题】:Groovy script xml parser for multiple files用于多个文件的 Groovy 脚本 xml 解析器
【发布时间】:2016-06-20 13:36:23
【问题描述】:

嗨,我的 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')

谢谢

里昂

【问题讨论】:

    标签: java xml groovy


    【解决方案1】:

    首先,我建议你把你拥有的东西放到一个函数中;这是很好的编码实践,提高了可读性。

    现在要对目录中的每个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")
    }
    

    如果你愿意,你也可以从命令行在目录中添加阅读。

    【讨论】:

    • 非常感谢 Riley 迫不及待想尝试新代码快速问题,如果我的 xml 文件的默认文件夹是 G://incoming_files 我会更改为新文件(“G://传入文件”)?
    • 那行得通,谢谢我现在正在尝试将输出文件的输出文件夹更改为 G://Outgoing_Files 而不是默认目录有没有办法在 groovy 中更改目录?
    • @Leon 是的!您可以将其添加到 stripTag stripTag(input, "G://Outgoing_Files/" + input.name + "_out.txt") 的调用中,也可以将其添加到它在 stripTag def file = new File ("G://Outgoing_Files/" + outputFile) 中创建输出文件的位置
    • 我能再挑你的脑筋吗?我需要列出目录中的所有文件,并将文件名插入到 oracle 表中,我使用 String conceptString = conceptList.join(',') sql.execute("插入 LDS.FILES(FILENAME) 值 (?)", [conceptsString])
    • @Leon 我很确定您需要更多地拆分文件以进行插入。试试String conceptsString = "(" + conceptList.join('),(') + ")"; sql.execute("insert into LDS.FILES(FILENAME) values ?", [conceptsString]) 。从此页面link:“使用 VALUES 语法的 INSERT 语句可以插入多行。为此,请包含多个列值列表,每个列表括在括号中并用逗号分隔。”
    猜你喜欢
    • 2017-06-10
    • 2021-12-31
    • 2013-02-21
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多