2011-10-17 91 views

回答

11

運行這在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 
+0

權, 很容易。現在我看到我正在做的一切正確:)我只忘了序列化輸出。謝謝! – Lukasz

1

增加一個屬性是一樣的閱讀它:

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>