用 handlebars.js 语句替换 XML 节点

Replace XML nodes with handlebars.js statements

我正在尝试为非程序员构建一种简单的方法来在 XML 文件中定义循环和条件逻辑。

我决定使用 <Loop></Loop><Condition></Condition> 标签来处理这些情况。这个想法是循环和条件标记将被 XML 中的 handlebars.js #each 和 #if 语句替换,例如

<Meeting>
    <Loop Target="People">
        <Person> 
            <Name>{{Name}}</Name>
            <Surname>{{Surname}}</Surname>
        </Person>
    </Loop>
</Meeting>

最终需要成为

<Meeting>
    {{#each People}}
        <Person> 
            <Name>{{Name}}</Name>
            <Surname>{{Surname}}</Surname>
        </Person>
    {{/each}}  
</Meeting>
 

对于 Condition 标签被转换为 handlebars if 语句也是如此。

我曾尝试使用 .Net 的 XDocument 库,但我正在努力弄清楚如何真正实现这一点(IXmlLineInfo 实例没有为我提供足够的信息)。

似乎我可能需要一种方法来解析原始字符串以获取开始标签和结束标签的开始和结束位置,以便直接进行文本替换。但我不确定如何以一种可以处理可编辑文本附带的大量边缘情况的方式来执行此操作。

我能够在不需要使用原始字符串操作或使用 IXmlLineInfo.

的情况下完成此操作

当遇到循环元素时,我只是:

//1. add the opening handlerbars code to the parent elemnet before the Loop element
loopNode.AddBeforeSelf("{{#each " + collection.Value + "}}");

//2. add all the loop element's children to the parent element just after the handlebars code
loopNode.AddBeforeSelf(loopNode.Elements());

//3. Add the closing handlebars statement to the parent after the Loop element
loopNode.AddAfterSelf("{{/each}}");

//4. Then finally remove the Loop element from the DOM
loopNode.Remove();

剩下的正是我需要发送到车把渲染器中的内容。