1

xml 形式で保存された word 文書があります。このドキュメントでは、$name のような GString タグがいくつかあります。

私の Groovy コードでは、xml ファイルをロードして、この GString タグを次のように置き換えます。

    def file = new File ('myDocInXml.xml')
    def name = 'myName'
    file.eachLine { line ->
        println line
    }

しかし、うまくいきません。GString タグが変数 'name' に置き換えられません。

誰でも私を助けることができますか?

THX

4

3 に答える 3

5

ここでテンプレートを使用することをお勧めします。xmmlファイルをテンプレートとしてロードし、プレースホルダーを置き換えるバインディングを作成します。簡単な例は次のようになります

def xml='''
<books>
<% names.each { %>
<book>
 $it
</book>
<%}%>

</books>
'''
def engine=new groovy.text.SimpleTemplateEngine()
def template=engine.createTemplate(xml)
def binding=[names:['john','joe']]
template.make(binding)
于 2009-06-12T07:39:08.087 に答える
0

しかし、かなり古い質問ですが、問題http://jira.codehaus.org/browse/GROOVY-2505はまだ解決されていません... Apache StrSubstitutor クラスを使用して、GString 置換のように動作する優れた回避策があります。私にとっては、テンプレートを作成するよりも快適です。XML ファイルで GStrings を使用できます。

import org.apache.commons.lang.text.StrSubstitutor

strResTpl = new File(filePath + "example.xml").text

def extraText = "MY EXTRA TEXT"

map = new HashMap();
map.put("text_to_substitute", "example text - ${extraText}")

def result = new StrSubstitutor(map).replace(strResTpl);

XML ファイル:

<?xml version="1.0" encoding="UTF-8"?>
<eample>
    <text_to_substitute>${text_to_substitute}</text_to_substitute>
</example>

結果:

<?xml version="1.0" encoding="UTF-8"?>
<eample>
    <text_to_substitute>example text - MY EXTRA TEXT</text_to_substitute>
</example>
于 2014-08-26T17:02:14.377 に答える