我需要 C# 逻辑来分析 XML 文件中的某些条件。逻辑应该能够评估条件并告诉我最终结果是真还是假:
例子:1: 规则 (A AND B AND C) 在 XML 文件中表示如下:
<Evaluate>
<!-- (A AND B AND C)-->
<AND>
<Condition Name="A" Operator="!=" Value="0"/>
<Condition Name="B" Operator="!=" Value="0"/>
<Condition Name="C" Operator="==" Value="17"/>
</AND>
</Evaluate>
我知道这很简单,但下面是一些需要从 C# 代码评估的复杂规则: 示例:2:
<Evaluate>
<!-- (A AND B) OR C -->
<OR>
<Condition Name="C" Operator="==" Value="17"/>
<AND>
<Condition Name="A" Operator="!=" Value="0"/>
<Condition Name="B" Operator="!=" Value="0"/>
</AND>
</OR>
</Evaluate>
示例:3:
<Evaluate>
<!-- (A) OR ((B AND C) OR D)-->
<OR>
<Condition Name="A" Operator="!=" Value="0"/>
<OR>
<Condition Name="D" Operator="!=" Value="0"/>
<AND>
<Condition Name="B" Operator="!=" Value="0"/>
<Condition Name="C" Operator="!=" Value="0"/>
</AND>
</OR>
</OR>
</Evaluate>
示例:4:
<Evaluate>
<!-- (A AND B) OR ((C AND D) OR E)-->
<OR>
<AND>
<Condition Name="A" Operator="!=" Value="0"/>
<Condition Name="B" Operator="!=" Value="0"/>
</AND>
<OR>
<Condition Name="E" Operator="!=" Value="0"/>
<AND>
<Condition Name="C" Operator="!=" Value="0"/>
<Condition Name="D" Operator="!=" Value="0"/>
</AND>
</OR>
</OR>
</Evaluate>
向您解释有关 Xml 节点的信息:
<Condition Name="D" Operator="!=" Value="0"/>
表示(D != 0)与否。
我们将不胜感激。
请您参考如下方法:
我给你做了一个例子
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
var dict = new Dictionary<string, int>();
dict["A"] = 1;
dict["B"] = 0;
dict["C"] = 17;
var result = Evaluate(doc.FirstChild,dict);
}
static bool Evaluate(XmlNode node, IDictionary<string, int> dict)
{
switch (node.Name)
{
case "Evaluate":
return Evaluate(node.FirstChild.NextSibling, dict); // Ignore first comment
case "Condition":
return Condition(node, dict);
case "AND":
return And(node, dict);
case "OR":
return Or(node, dict);
default:
throw new NotSupportedException();
}
}
private static bool Or(XmlNode root, IDictionary<string, int> dict)
{
var result = false; // Starting with false, because It will be true when at least condition is true
foreach (XmlNode node in root.ChildNodes)
{
result |= Evaluate(node, dict);
}
return result;
}
private static bool And(XmlNode root, IDictionary<string, int> dict)
{
var result = true;
foreach (XmlNode node in root.ChildNodes)
{
result &= Evaluate(node, dict);
}
return result;
}
private static bool Condition(XmlNode node, IDictionary<string, int> dict)
{
var name = node.Attributes["Name"].Value;
var value = node.Attributes["Value"].Value;
var opt = node.Attributes["Operator"].Value;
switch (opt)
{
case "==":
return dict[name] == int.Parse(value);
case "!=":
return dict[name] != int.Parse(value);
default:
throw new NotSupportedException();
}
}
