StringTemplate invalid character '<' when reading XML Template

醉酒当歌 提交于 2019-12-12 10:36:31

问题


I am trying to create a simple XML-Template which so far only consists of:

<?xml version="1.0"?>

I read the file like this:

    STGroup group = new STGroupDir("templates");
    ST st = group.getInstanceOf("report");
    st.add("analysis", ana);
    String result = st.render();
    System.out.println(result);

And the result is several error messages:

report.st 1:1: invalid character '<'
report.st 1:1: invalid character '?'
report.st 1:19: invalid character '?'
report.st 1:20: invalid character '>'
report.st 1:2: no viable alternative at input 'xml'

I have seen other people reading HTML tempaltes that also use tags. So what am I doing wrong?


回答1:


Okay it seems I overlooked that you need to specify templates in a different snytax. Allthough this was not obvious from the examples I used:

My working template looks different now:

report (analysis) ::= <<
<?xml version="1.0"?>
>>

In addition I also changed the delimeters:

STGroup group = new STGroupDir("templates",'$','$');



回答2:


I've found that you can escape the angle bracket as well:

report(analysis) ::= <<
\<?xml version="1.0"?>
>>

Note the \ right before the <?xml -- additionally it's smart enough not to require another escape at the ?> closing bracket.

And I believe what Terrence Parr is suggesting about model/view separation is that the view never really has an opportunity to manipulate the underlying data structure (or model) passed to the template. This is accomplished by "applying" a template to the data or collection, rather than looping in the template over the data. Perhaps that is subtle, and perhaps practically (in the case of designers) a bit too pure.




回答3:


Alternatively, you can use STRawGroupDir if you don't want to use group file syntax. This class is similar to STGroupDir, but specifically for loading files like XML and HTML.

http://www.stringtemplate.org/api/org/stringtemplate/v4/STRawGroupDir.html



来源:https://stackoverflow.com/questions/10414622/stringtemplate-invalid-character-when-reading-xml-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!