怎样使用Groovy给XML增加特性?
问:
在Groovy中,我需要增加一个特性(attribute)到XML的根元素。我想使用 XmlSlurper。该怎样做?增加元素是很简单。
答:
在Groovy Console 运行以下代码,结果良好。
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) [email protected] = ‘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
增加一个特性与读一个特性是一样的:
import groovy.xml.StreamingMarkupBuilder def input = ‘‘‘ <thing> <more> </more> </thing>‘‘‘ def root = new XmlSlurper().parseText(input) [email protected] = ‘new‘ def outputBuilder = new StreamingMarkupBuilder() String result = outputBuilder.bind{ mkp.yield root } println result
将生成:
<thing stuff=‘new‘><more></more></thing>
来源: <http://stackoverflow.com/questions/7795494/how-to-add-xml-attribute-using-groovy>
时间: 2024-10-11 10:50:27