Syntax for conditional attributes

Coordinator
Feb 20, 2012 at 4:02 PM
Edited Feb 23, 2012 at 9:31 AM

The feature request "Add ability to conditionally remove attributes from an element" describes the ability to remove attributes on an element conditionally.

In order to support this, a new syntax would be required.

Approach 1: the element containing the attributes also contains an applyAttributeWhen attribute. This contains a list (delimited with start and stop square brackets) of the names of each attribute to possibly remove, a separator, and then the condition required to keep the attribute.

In the example below, the debug attribute would be retained if buildType = "debug".

<configuration xmlns:cg="http://roblevine.co.uk/Namespaces/ConfigGen/1/0/">
 
  <compilation cg:applyAttributeWhen="[debug:$buildType='debug']" debug="true" 
alwaysHere="true">
    <subElement />
    <anotherSubElement />
  </compilation>
  
</configuration>

This is probably the simplest approach but is not very easy to read IMHO.

Approach 2: The conditional attribute is prefixed with cg:condition-{attributeName}. The value part starts with the condition required to include the attribute, a delimiter, and the attribute value (if it is kept).

In the example below, an attribute debug='true' would be added if buildType = "debug"

<configuration xmlns:cg="http://roblevine.co.uk/Namespaces/ConfigGen/1/0/">

 <compilation cg:conditional-debug="$buildType='debug'|true" alwaysHere="true">
    <subElement />
	<anotherSubElement />
 </compilation>
  
</configuration>

This is more concise and readable, IMHO, than approach 1, but it makes it impossible to ever write a schema to validate the configGen namespace as there are now an arbitrary number of attribute names, that start with conditional-{attributeName}.

Approach 3: A child element, e.g. RemoveAttributeFromParent is created to contain the information on the attribute to remove on its parent.

In the example below, the debug attribute on the compilation element will be removed if debug is not true.

<configuration xmlns:cg="http://roblevine.co.uk/Namespaces/ConfigGen/1/0/">

 <compilation debug='true'>
    <cg:RemoveAttributeFromParent attributeName='debug' removeWhen="$debug!='true'" />
    <subElement />
    <anotherSubElement />
 </compilation>
  
</configuration>

Slightly more verbose than the others, but probably the most readable.

These all have their pros and cons - so please let me know your opinions, and suggest alternatives!

Thanks

Coordinator
Feb 23, 2012 at 9:31 AM

NOTE: v0.3.2.5 (changeset ec9520289833 ) includes experimental support for this, using the approach 3 syntax above.