如何使用Groovy的MarkupTemplateEngine向标记添加名称空间

时间:2015-01-25 21:07:53

标签: groovy

有没有办法使用MarkupTemplateEngine来创建带有命名空间的标记?

我希望能够做到这样的事情:    sp.setNameSpaceDeclaration(' http://example.org/myns&#39)

 xmlDeclaration()

 cars(sp.ns) {
     cars.each {
       car(make: it.make, model: it.model)
       sp.brand(attribute:'year', 'my text')
     } 
  }

并获取

<?xml version='1.0' encoding='UTF-8'?>
<cars xmlns:sp="http://example.org/myns">
    <car make='Peugeot' model='508'/>\
    <sp:brand attribute='year'>my text</sp:brand>
    <car make='Toyota' model='Prius'/>
    <sp:brand attribute='year'>my text</sp:brand>
</cars>

我找到了一种方法来调整模板以获得我想要的结果。可能有更好的解决方案,但现在我正在使用:

 xmlDeclaration()
 cars('xmlns:sp':"http://example.org/myns") {
   cars.each {
      car(make: it.make, model: it.model)
     'sp:brand'(attribute:'year', 'my text')
   }
 }     

2 个答案:

答案 0 :(得分:2)

你几乎就在那里。我已将StreamingMarkupBuilder初始化包括在内以获得完整性

def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'

def cars = builder.bind {
    mkp.xmlDeclaration()
    namespaces << [sp:'http://example.org/myns']
    cars('xmlns:sp':"http://example.org/myns") {
       cars.each {
          car(make: it.make, model: it.model)
         'sp:brand'(attribute:'year', 'my text')
       }
    }     
}

答案 1 :(得分:0)

我想使用模板文件,所以我现在处理它的方式是:

cars.tpl 模板:

 xmlDeclaration()
 cars('xmlns:sp':"http://www.w3schools.com/furniture") {
   comment commentTest
   newLine()
   cars.each {
      car(make: it.make, model: it.model)
      newLine()
      'sp:brand'(attribute:'year', 'my text')
      newLine()
   }
}

程序

    URL url = this.getClass().getResource("/cars.tpl");
    File markupTemplate = new File(url.getFile());

    TemplateConfiguration config = new TemplateConfiguration();
    config.setAutoNewLine(true);
    config.setAutoIndent(true);
    config.setDeclarationEncoding('UTF-8');
    MarkupTemplateEngine engine = new MarkupTemplateEngine(config);

    Template template = engine.createTemplate(markupTemplate);
    def model = [commentTest: 'alberto', cars: [new Car(make: 'Peugeot', model: '508'), new Car(make: 'Toyota', model: 'Prius')]]

    def fout = new File("C:\\code\\cesa\\src\\test\\resources\\cars.xml")
    fout.withWriter('UTF-8') {writer ->
        template.make(model).writeTo(writer)
    }