4
我需要在Groovy的XML片段的根元素中添加@屬性。我想用XmlSlurper
。怎麼做?添加元素很簡單。如何使用Groovy添加XML屬性?
我需要在Groovy的XML片段的根元素中添加@屬性。我想用XmlSlurper
。怎麼做?添加元素很簡單。如何使用Groovy添加XML屬性?
運行這在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)
[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>
權, 很容易。現在我看到我正在做的一切正確:)我只忘了序列化輸出。謝謝! – Lukasz