Reputation: 55
I need a way to add an XML attribute 'POSITON' to an XML element 'node' conditionally. Currently I'm doing the condition check first and then creating the node.
if (lvl == 2)
node = <node COLOR={ color } CREATED={ epochTimeMillis } ID={ idGen } POSITION={ position } LINK={ link } MODIFIED={ epochTimeMillis } STYLE="bubble" TEXT={ f.getName() }>
<edge COLOR={ color } STYLE={ style } WIDTH={ width }/>
</node>
else
node = <node COLOR={ color } CREATED={ epochTimeMillis } ID={ idGen } LINK={ link } MODIFIED={ epochTimeMillis } STYLE="bubble" TEXT={ f.getName() }>
<edge COLOR={ color } STYLE={ style } WIDTH={ width }/>
</node>
}
Upvotes: 1
Views: 832
Reputation: 12998
One way is to create the snippet before:
val pos =
if (lvl == 2) {
"position = ..."
} else {
""
}
and to always insert it in the result.
This could by extended by using an Option with embedded map in combination with string interpolation.
val pos =
if (lvl == 2) {
Some(position)
} else {
None
}
with
pos.map(v => s"position = $v")
Upvotes: 0
Reputation: 35443
A slightly cleaner way to do the same thing @senia suggests is:
val posOpt = if (lvl2) Some(myPosition) else None
val xml = <mydata position={posOpt orNull}/>
Upvotes: 1
Reputation: 38045
Using "null" is not a good practice, but in this case it would help you:
scala> <root ta={ if (true) "true" else null } fa={ if (false) "false" else null } />
res0: scala.xml.Elem = <root ta="true" ></root>
Upvotes: 3