怎样使用Groovy给XML增长特性

怎样使用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

相关文章
相关标签/搜索