我有一个程序,它使用XML格式的规则来创建运行时的可执行代码.我必须使用自己的方言定义一些动作和逻辑结构.我有OR,AND,和NOT构造,现在我需要实现IF..THEN..ELSE.
我试图提出一个有意义的语法,这是我到目前为止所拥有的:
<IF id='if-1'>
<TIME from="5pm" to="9pm" />
</IF>
<THEN id='if-1'>
<...some actions defined.../>
</THEN>
<ELSE id='if-1'>
<...other set of actions defined here.../>
</ELSE>
Run Code Online (Sandbox Code Playgroud)
如果看起来很难读,但我没有看到更清晰的方式来代表这一点而不做太多的嵌套.有没有人有建议?(此时不使用XML不是一个选项:))
也许是在XML中编码条件结构的另一种方法:
<rule>
<if>
<conditions>
<condition var="something" operator=">">400</condition>
<!-- more conditions possible -->
</conditions>
<statements>
<!-- do something -->
</statements>
</if>
<elseif>
<conditions></conditions>
<statements></statements>
</elseif>
<else>
<statements></statements>
</else>
</rule>
Run Code Online (Sandbox Code Playgroud)
我个人认为if/then/else需要以某种方式联系起来.
<IF something>
<some actions>
<THEN something>
<some actions>
</THEN>
<ELSE something>
<some actions>
</ELSE>
</IF>
Run Code Online (Sandbox Code Playgroud)
前段时间遇到类似的问题,我决定采用通用的“switch ... case ... break ... default”类型的解决方案以及带有条件执行的 arm 样式指令集。使用嵌套堆栈的自定义解释器用于解析这些“程序”。此解决方案完全避免了 id 或标签。我所有的 XML 语言元素或“指令”都支持“条件”属性,如果该属性不存在或计算结果为真,则执行元素的指令。如果有一个“exit”属性求值为真且条件也为真,则同一嵌套级别的以下一组元素/指令既不会被求值也不会执行,执行将继续执行下一个元素/指令父级。如果没有“退出”或评估结果为假,则程序将继续执行下一个元素/指令。例如,您可以编写这种类型的程序(提供一个 noop“语句”会很有用,并且将值和/或表达式分配给“变量”的机制/指令将证明非常方便):
<ins-1>
<ins-11 condition="expr-a" exit="true">
<ins-111 />
...
</ins11>
<ins-12 condition="expr-b" exit="true" />
<ins-13 condition="expr-c" />
<ins-14>
...
</ins14>
</ins-1>
<ins-2>
...
</ins-2>
Run Code Online (Sandbox Code Playgroud)
如果 expr-a 为真,则执行顺序为:
ins-1
ins-11
ins-111
ins-2
Run Code Online (Sandbox Code Playgroud)
如果 expr-a 为假而 expr-b 为真,那么它将是:
ins-1
ins-12
ins-2
Run Code Online (Sandbox Code Playgroud)
如果 expr-a 和 expr-b 都是假的,那么我们将有:
ins-1
ins-13 (only if expr-c evaluates to true)
ins-14
ins-2
Run Code Online (Sandbox Code Playgroud)
附注。我使用了“exit”而不是“break”,因为我使用了“break”来实现“断点”。如果没有某种断点/跟踪机制,这样的程序很难调试。
PS2。因为我的日期时间条件与您的示例以及其他类型的条件相似,所以我还实现了两个特殊属性:“from”和“until”,如果存在,它们也必须评估为真,就像“条件”一样,并且使用了特殊的快速日期时间检查逻辑。