现在的位置: 首页 > 综合 > 正文

Parse the StringTemplate expression

2012年11月05日 ⁄ 综合 ⁄ 共 2707字 ⁄ 字号 评论关闭
    If you need to get the attributes list that referenced in a StringTemplate, as well as which specific templates that invoked by it, you need to parse the StringTemplate expression. The following code snippet demonstrates how to do this using StringTemplate.
using Antlr.StringTemplate;
using Antlr.StringTemplate.Language;
using antlr.collections;

public partial class Default4 : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        
//define the template
        StringTemplate st = new StringTemplate(@"
<html>
<head>
    $StyleImport$
    $ScriptImport$
</head>
<body>
    $_b_1100()$
    $users:_t_13(userName=attr.Name):_b_37(age=12)$
    $users:{<li>$attr.Name$</li>}$
    $Copyright$
</body>
</html>
");
        
//loop to print all nodes in the expression tree
        for (int i = 0; i < st.Chunks.Count; i++)
        {
            
if (st.Chunks[i] is ASTExpr)
            {
                RecurTokens((st.Chunks[i] 
as ASTExpr).AST, 0);
            }
        }
    }

    private void RecurTokens(AST ast, int level)
    {
        
if (ast != null)
        {
            
//print current node
            for (int i = 0; i < level; i++)
                
this.Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
            
this.Response.Write(ast.Type.ToString("0#"+ "----" + ast.ToString().Replace("<""&lt;").Replace(">""&gt;"));
            
this.Response.Write("<br>");

            //recursive to the child nodes
            RecurTokens(ast.getFirstChild(), level + 1);
            
//recursive to the sibling nodes
            AST sibling = ast.getNextSibling();
            
while (sibling != null)
            {
                RecurTokens(
sibling, level + 1);
                sibling
= sibling.getNextSibling();
            }
        }
    }
}

    The output is like:
18----StyleImport
18----ScriptImport
07----include
       18----_b_1100
              06----ARGS
04----:
       04----:
              18----users
                     10----
                            18----_t_13
                                   06----ARGS
                                          19----=
                                                 18----userName
                                                        24----.
                                                               18----attr
                                                                      18----Name
              10----
                     18----_b_37
                            06----ARGS
                                   19----=
                                          18----age
                                                 33----12
04----:
       18----users
              10----
                     31----<li>$attr.Name$</li>
18----Copyright
    Now you should be aware of how to make those things to be done.

抱歉!评论已关闭.