import groovy.xml.StreamingMarkupBuilder// the original XMLdef input = "<foo><bar></bar></foo>"// add attributeName="attributeValue" to the rootdef root = new XmlSlurper().parseText(input)root.@attributeName = "attributeValue"// get the modified XML and check that it workeddef outputBuilder = new StreamingMarkupBuilder()String updatedXml = outputBuilder.bind{ mkp.yield root }assert "<foo attributeName="attributeValue"><bar></bar></foo>" == updatedXml
增加一個特性與讀一個特性是一樣的:
import groovy.xml.StreamingMarkupBuilderdef 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
增加特性是很簡單的:在Groovy Console 執行以下程式碼,結果良好。
import groovy.xml.StreamingMarkupBuilder// the original XMLdef input = "<foo><bar></bar></foo>"// add attributeName="attributeValue" to the rootdef root = new XmlSlurper().parseText(input)root.@attributeName = "attributeValue"// get the modified XML and check that it workeddef outputBuilder = new StreamingMarkupBuilder()String updatedXml = outputBuilder.bind{ mkp.yield root }assert "<foo attributeName="attributeValue"><bar></bar></foo>" == updatedXml
增加一個特性與讀一個特性是一樣的:import groovy.xml.StreamingMarkupBuilderdef 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
將生成:<thing stuff="new"><more></more></thing>