0

我有一个 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>

我将搜索名称“CustomObject”并使用此字符串删除所有兄弟姐妹的成员:

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>

我仍在努力掌握这一点,所以任何帮助都会很棒

4

1 回答 1

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 )
}
于 2018-03-23T21:45:35.750 回答