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)
}
}
}
过滤器闭包参数是一行,而不是File。如何编写自定义过滤器来操作XML文件
filter(myFilterType)
无法找到有关创建自定义过滤器的示例/文档。
答案 0 :(得分:0)
过滤器适用于行,而不适用于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>