如何使用MarkupBuilder动态调整XML?

时间:2014-05-03 04:21:54

标签: templates groovy

我有一个XML模板,我希望能够动态地向模板添加/删除/更新属性,我该怎么办?

感谢。

1 个答案:

答案 0 :(得分:3)

从标题和问题本身不清楚您是否正在寻找动态修改XML或XML模板(它们是两个不同的实体),因此总结了两个选项:

修改XML中的属性

def xml = '''
<cars>
  <car type='sedan'>Honda</car>
  <car type='sedan' category='standard'>Toyota</car>
</cars>
'''

def slurper = new XmlSlurper().parseText(xml)

//Add
slurper.car.find { it.text() == 'Honda' }.@year = '2013'

//Modify
slurper.car.find { it.text() == 'Toyota' }.@type = 'Coupe'

//Delete
slurper.car.find { it.text() == 'Toyota' }.attributes().remove( 'category' )

groovy.xml.XmlUtil.serialize( slurper )

使用XmlTemplateEngine

从模板创建XML

摘录自XmlTemplateEngine API:

def binding = [firstname:"Jochen", lastname:"Theodorou", 
               nickname:"blackdrag", salutation:"Dear"]
 def engine = new groovy.text.XmlTemplateEngine()
 def text = '''<?xml version="1.0" encoding="UTF-8"?>
 <document xmlns:gsp='http://groovy.codehaus.org/2005/gsp' 
           xmlns:foo='baz' type='letter'>
   <gsp:scriptlet>def greeting = "${salutation}est"</gsp:scriptlet>
   <gsp:expression>greeting</gsp:expression>
   <foo:to>$firstname "$nickname" $lastname</foo:to>
   How are you today?
 </document>
 '''
 def template = engine.createTemplate(text).make(binding)
 println template.toString()

使用MarkupTemplateEngine

从模板创建XML

从Groovy 2.3开始,我们也可以使用MarkupTemplateEngineDSL builder样式创建xml:

import groovy.text.markup.*
import groovy.text.Template

def xmlTemplate = '''
xmlDeclaration()
cars {
   cars.each {
       car(make: it.make, model: it.model)
   }
}
'''
class Car {
    String make, model
}
def model = [
    cars: [
        new Car(make: 'Peugeot', model: '508'), 
        new Car(make: 'Toyota', model: 'Prius')
    ]
]

def render(xmlTemplate, model) {
    MarkupTemplateEngine engine = 
        new MarkupTemplateEngine(
           new TemplateConfiguration( autoNewLine: true, autoIndent: true ) )
    Template template = engine.createTemplate( xmlTemplate )
    Writable output = template.make( model )
    def writer = new StringWriter()
    output.writeTo( writer )
    println writer
}

render( xmlTemplate, model )