Gradle zip:如何通过添加新节点来过滤XML文件,例如,

task mytask(type: Zip) {

    from ("foo/bar") {

        include "config.xml"
        filter {
             def root = new XmlParser().parser(configXml_inputStream)
             root.hello.world.append(aNode)
             groovy.xml.XmlUtil.serialize(root, configXml_outputStream)
        }
    }

}

过滤器关闭参数是一行,而不是文件。如何编写自定义过滤器来处理XML文件
filter(myFilterType)

找不到有关创建自定义过滤器的示例/文档。

最佳答案

过滤器在行上工作,而不是xml节点。以下示例说明了使用行的替换,但请注意,这是xml的一种奇怪方法,在一般情况下不起作用。

鉴于此foo/bar/config.xml:

<root>
    <hello>
        <world>
        </world>
    </hello>
</root>

假定仅要增加一个<world>元素,然后考虑此build.gradle:
task mytask(type: Zip) {
    archiveName "config.zip"

    from ("foo/bar") {
        include "config.xml"

        filter { line ->
            def result = line

            if (line.trim() == '<world>') {
                def buffer = new StringBuilder()
                buffer.append(line + "\n")
                buffer.append('<aNode type="example">' + "\n")
                buffer.append('</aNode>')
                result = buffer.toString()
            }

            result
        }
    }
}

那么config.xml中的config.zip是:
<root>
    <hello>
        <world>
<aNode type="example">
</aNode>
        </world>
    </hello>
</root>

10-07 13:29
查看更多