怎樣使用Groovy給XML增長特性?ui
問:spa
在Groovy中,我須要增長一個特性(attribute)到XML的根元素。我想使用 XmlSlurper。該怎樣作?增長元素是很簡單。code
答:orm
在Groovy Console 運行如下代碼,結果良好。xml
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
增長一個特性與讀一個特性是同樣的:get
import groovy.xml.StreamingMarkupBuilder def input = ''' <thing> <more> </more> </thing>''' def root = new XmlSlurper().parseText(input) root.@stuff = 'new' def outputBuilder = new StreamingMarkupBuilder() String result = outputBuilder.bind{ mkp.yield root } println result
將生成:input
<thing stuff='new'><more></more></thing>
來源: <http://stackoverflow.com/questions/7795494/how-to-add-xml-attribute-using-groovy>it