I have the following XML file:
<?xml version="1.0" encoding="utf-8" ?>
<strategies>
<strategy name="God Class">
<gate type="AND">
<rule>
<metric>LOC</metric>
<comparison>greater than</comparison>
<value>850</value>
</rule>
<rule>
<metric>FANIN</metric>
<comparison>greater than</comparison>
<value>850</value>
</rule>
<rule>
<metric>FANOUT</metric>
<comparison>greater than</comparison>
<value>850</value>
</rule>
</gate>
</strategy>
<strategy name="TClass">
<gate type="OR">
<gate type="AND">
<rule>
<metric>LOC</metric>
<comparison>greater than</comparison>
<value>100</value>
</rule>
<rule>
<metric>NOM</metric>
<comparison>greater than</comparison>
<value>200</value>
</rule>
</gate>
<rule>
<metric>NOPAR</metric>
<comparison>greater than</comparison>
<value>300</value>
</rule>
</gate>
</strategy>
</strategies>
Now I try to parse this document and extract the rules. The first strategy is easy with the following code:
public static void parseRules()
{
XDocument document = XDocument.Load(FILE);
XElement root = document.Root;
foreach (XElement elem in root.Elements())
{
String name = elem.Attribute(STRATEGY_NAME).Value;
XElement gate = elem.Element(GATE_NAME);
List<Rule> rules = new List<Rule>();
foreach (XElement r in gate.Elements())
{
String metric = r.Element(METRIC_NAME).Value;
String comparisation = r.Element(COMPARISON_NAME).Value;
int threshold = Convert.ToInt32(r.Element(VALUE_NAME).Value);
Rule rule = null;
if (comparisation.Equals(GREATER_THAN_NAME))
{
rule = new Rule(metric, Rule.GREATHER_THAN, threshold);
}
else if (comparisation.Equals(SMALLER_THAN_NAME))
{
rule = new Rule(metric, Rule.SMALLER_THAN, threshold);
}
rules.Add(rule);
}
ISpecification spec = rules.ElementAt(0);
if (gate.Attribute(TYPE_NAME).Value.Equals(AND))
{
for (int i = 1; i < rules.Count; i++)
{
spec = spec.And(rules.ElementAt(i));
}
}
else if (gate.Attribute(TYPE_NAME).Value.Equals(OR))
{
for (int i = 1; i < rules.Count; i++)
{
spec = spec.Or(rules.ElementAt(i));
}
}
DetectionStrategy strategy = new DetectionStrategy(spec, name);
}
}
}
Obviously this only works for XML files that have only rules in one gate and not another gate as in the second example. However I'm not able to parse nested gates. Any hints where to start?