groovy - 如何使用 Groovy 添加 XML 属性?

标签 groovy

我需要在 Groovy 中将 @ 属性添加到 XML 片段的根元素。我想使用 XmlSlurper 。怎么做?添加元素很容易。

最佳答案

在 Groovy 控制台中运行它以验证它是否有效

import groovy.xml.StreamingMarkupBuilder

// the original XML
def input = "<foo><bar></bar></foo>"

// add attributeName="attributeValue" to the root
def root = new XmlSlurper().parseText(input)
root.@attributeName = 'attributeValue'

// get the modified XML and check that it worked
def outputBuilder = new StreamingMarkupBuilder()
String updatedXml = outputBuilder.bind{ mkp.yield root }

assert "<foo attributeName='attributeValue'><bar></bar></foo>" == updatedXml

关于groovy - 如何使用 Groovy 添加 XML 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7795494/

相关文章:

mysql - 如何使用mysql在g​​roovy中存储持续时间

groovy - Gitblit Hook 日志

datetime - 使用埃塞俄比亚年表格式化 Joda Time 不显示月份名称

java - 如何在 Groovy Jenkins 管道中使用全局外部 Java 库中的方法?

jenkins - 如何将Groovy类导入Jenkinfile?

javascript - Groovy:在静态作用域中找到表观变量 'classVar',但未引用局部变量、静态字段或类

dictionary - 从 Groovy 映射中删除给定键

grails - 如何导入groovyx.net.http

grails - 执行Geb测试之前如何登录

java - 编译的 Groovy 脚本