使用groovy从xml文档中删除值

时间:2018-03-23 20:04:44

标签: xml groovy xmlslurper groovyshell jenkins-groovy

我有一个groovy系统批处理脚本,需要读入XML文档,更改值,然后保存它。

我已经弄清楚如何读取值并编写它。我无法弄清楚我的生活如何移除'成员'及其价值观。我需要能够删除所有成员并用自定义文件名替换它我无法弄明白。

XML看起来像这样:

<types>
    <members>*</members>
    <members>Account</members>
    <members>Activity</members>
    <members>Contact</members>
    <members>Task</members>
    <members>User</members>
    <members>ContentVersion</members>
    <name>CustomObject</name>
</types>

我会搜索名称&#34; CustomObject&#34;并使用此字符串删除所有兄弟姐妹的成员:

def replace = "MyCustomFile"

所以XML会这样:

<types>
    <members>MyCustomFile</members>
    <name>CustomObject</name>
</types>

我尝试了以下在网上找到的代码

println "Testing Slurper"
def root = new XmlSlurper().parse(new File(theFile))
root.types.each { types ->
println "names: ${types.name}"
    types.members.each {
        println "members: " + it.text()
    }
}

    println "Testing replace"
    def book = "Booking__c"


    def cleanUpNode(node) {
        println node
        def childs = node.children()

        def remove = []
        childs.each {
            if (it instanceof Node) {

                if (!it.children()) {
                    remove.add it
                } else {
                    cleanUpNode it
                    if (!it.children()) {
                        remove.add it
                    }
                }
            }
        }

        remove.each { node.remove(it) }
    }

    cleanUpNode root.types.name

实际上并没有删除任何内容,而是输出:

  <tag0:types>
    <tag0:members>*</tag0:members>
    <tag0:members>Account</tag0:members>
    <tag0:members>Activity</tag0:members>
    <tag0:members>Contact</tag0:members>
    <tag0:members>Task</tag0:members>
    <tag0:members>User</tag0:members>
    <tag0:members>ContentVersion</tag0:members>
    <tag0:name>CustomObject</tag0:name>
  </tag0:types>

我仍然试图掌握这一点,所以任何帮助都会很棒

1 个答案:

答案 0 :(得分:1)

您可以这样做:

List newMembersToAdd = ['myCustomFile', 'anotherCustomFile']

Node xml = new XmlParser(false, false, false).parse("myXml.xml")

xml.members?.each {
    xml.remove it
}

newMembersToAdd.each { String newMember ->
    new Node(xml, 'members', newMember)
}

new File("myNewXml.xml").withWriter { writer ->
    def printer = new XmlNodePrinter( new PrintWriter(writer) )
    printer.preserveWhitespace = true
    printer.print( xml )
}