2011-10-17 24 views
4

@属性をGroovyのXMLフラグメントのルート要素に追加する必要があります。 XmlSlurperを使用します。どうやってするの?要素の追加は簡単です。Groovyを使用してXML属性を追加する方法は?

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 

はあなたを与えるだろう::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 

答えて

11

実行して、それを読んで同じである

<thing stuff='new'><more></more></thing> 
+0

右、それは簡単だった。今私はすべてを正しくやっているのを見ています:)出力をシリアル化するのを忘れてしまっただけです。ありがとう! – Lukasz

1

機能することを確認するために

関連する問題