如何使用 Groovy 添加 XML 属性?

2024-03-31

我需要将 @ 属性添加到 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Groovy 添加 XML 属性? 的相关文章

随机推荐